Why is my UPDATE Query not working? - mysql

I have the following update query but for some reason it's not working. I think it's something to do with the "id = '".$id."' but I've tried about three different ways and I cannot seem to get it to work. I've written update queries before with no problems but for some reason this one is being a pain. Thanks in advance.
$id = $_GET['id'];
$speaker = mysql_real_escape_string($_POST['speaker']);
$message = $_POST['message'];
$title = mysql_real_escape_string($_POST['title']);
$date = $_POST['date'];
$day = $_POST['day'];
$password = mysql_real_escape_string($_POST['password']);
$complete = $_POST['complete'];
$title = ucwords(strtolower($title));
if ($complete && ($password == "*****"))
{
$db = mysql_connect($hostname, $username, $password) or die(mysql_error());
mysql_select_db($dbname,$db) or die(mysql_error());
mysql_query("UPDATE sermons SET speaker = '$speaker', message = '$message', title = '$title', date = '$date', day = '$day' WHERE id = '$id'");
$num_rows = mysql_num_rows(mysql_query("SELECT speaker, message, title, date, day FROM sermons WHERE speaker = '$speaker' AND message = '$message' AND title = '$title' AND date = '$date' AND day = '$day'", $db));
if ($num_rows == 1)
echo "<script type='text/javascript'> alert('Sermon Information Entered Successfully!'); </script>";
else
echo "<script type='text/javascript'> alert('Error! Please Try Again.'); </script>";
}
else if ($complete && ($password != "*****"))
{
echo "<script type='text/javascript'> alert('Incorrect Password! Please Try Again.'); </script>";
}

Because of id is Integer so this is correct code try thus :
mysql_query("UPDATE sermons SET speaker = '$speaker', message = '$message', title = '$title', date = '$date', day = '$day' WHERE id =".$id);
I expected it will be works.

Writing this as an answer as providing code in comments is difficult to read
Try changing
mysql_query("UPDATE sermons SET speaker = '$speaker', message = '$message', title = '$title', date = '$date', day = '$day' WHERE id = '$id'");
To
mysql_query("UPDATE sermons SET speaker = '$speaker', message = '$message', title = '$title', date = '$date', day = '$day' WHERE id = '$id'") or die(mysql_error());
Then add the error message to your question please.

Related

How do I get DateTime from mysql and set it to json format ready for highcharts

I started my project March last year and have almost got it right.
Trying to get data from mysql and put it in highcharts.
This is my query
<?php
$con = mysqli_connect("localhost","root","root","manortsc_test");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$sth = mysqli_query($con,"
SELECT DateTime,max(T)
FROM alldata
WHERE DATE(DateTime) = CURDATE() - INTERVAL 1 DAY
GROUP BY hour(DateTime)
"
);
$rows = array();
$rows['name'] = 'Outside';
while($r = mysqli_fetch_array($sth)) {
$rows['data'][] = $r['max(T)'];
}
$result = array();
array_push($result,$rows);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
The json output is missing the date and time
[{"name":"Outside","data":[17.5,16.3,15.6,15.1,14.4,14,14.1,16,18.5,21.7,24.1,26.9,28.3,29.6,30.6,31.1,31.8]}]
The graph shows okay (except datetime on x axis) and I cannot figure how to fix it. I have tried every way except the correct way. Any help would be appreciated.
Changed the query to this and now it works.
Thanks wergeld and Yuri for the assistance.
$sth = mysqli_query($con,"
SELECT DateTime,max(T)
FROM davisvp
WHERE DATE(DateTime) = CURDATE()
GROUP BY hour(DateTime)
"
);
$result = array();
$result['name'] = 'temperature';
while($row = mysqli_fetch_array($sth))
{
$date = strtotime($row['DateTime']);
$maxt = 1 * $row['max(T)'];
$result1 = array();
array_push($result1,$date);
array_push($result1,$maxt);
$result['data'][] = $result1;
}
echo json_encode($result, JSON_NUMERIC_CHECK);

adding a condition to a WHERE clause based on a passed variable value mysql

I am a relative novice and could use some help with this problem.
This will be used in a search filter situation.
Users need to search by a value and 1 or more other values passed by the search form.
$name = $_POST['name'];
$sdate = $_POST['sdate'];
$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
$vehicle = $_POST['vehicle'];
$triptype = $_POST['triptype'];
If any of these values are '' I do not want them in the query, If they contain a value I do want them in the query.
SELECT * FROM form_data WHERE `resp_person` = '$name',
IF $sdate != '' then `sdate` = '$sdate',
IF $startdate != '' then `sdate` = *all values between $startdate and $enddate*,
IF $triptype != '' then `triptype` = '$vehicle',
IF $vehicle != '' then `vehicle` = '$vehicle', `sdate`
ORDER BY `sdate` DESC, `stime` DESC")
I know the code is wrong but it should give you a good idea of what I am trying to accomplish. Any guidance would be greatly appreciated.
A better way is to not use string concatenation to build the entire query, but rather use an sql library that supports prepared statements, such as PDO.
$pdo = new PDO('... connection string ...', username, password);
$where = '';
$possible_values = array('name', 'sdate', 'startdate', 'enddate', 'vehicle', 'triptype' );
$params = array();
foreach($possible_values as $val)
{
if(isset($_POST[$val]))
{
$params[] = $_POST[$val];
if($where == '')
{
$where = "WHERE $val = ?";
}
else
{
$where .= " AND $val = ?";
}
}
}
$stmt = $pdo->prepare("SELECT * FROM form_data " . $where);
$stmt->execute($params);
In cases like this, I prefer to build the query in pieces...
$wheres = array(); // Collect things to AND together
if ($searchterm != 'All') $wheres[] = "subject LIKE '%searchterm'";
if (...) $wheres[] = "...'";
...
if (count($wheres) > 0)
$where_str = "WHERE " . implode(' AND ', $wheres);
else
$where_str = '';
$order_str = (...) ? "ORDER BY ..." : '';
$limit_str = $limit ? "LIMIT $limit" : '';
$query = "SELECT ... FROM foo $where_str $order_str $limit_str";
Oh, and don't forget to use escape the strings on any data coming in from a form -- else a user can do nasty things to the SQL statement!

Mysql query not inserting into database?

I am trying to insert data posted from a form into my database using the following MySQL statement but it is producing my error 'Oooops! *** **** ***'
I know there is a connection because before I insert anything I test the users email address to see if it already exists and if it does it redirects the user to login. and this works so if the email doesn't exist in the database then it is suppose to be inserting the form data but it isn't.
* can someone please show me where I am going wrong? I have made sure I am spelling the table names correct and everything and am 100% sure I have posted all my form data correctly.
<?php
session_start();
include("config.php");
include("verify.php");
//retrieve our data from POST
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$contactnum = $_POST['contactnum'];
$mobnum = $_POST['mobnum'];
$postcode = $_POST['postcode'];
$addres1 = $_POST['address1'];
$addres2 = $_POST['address2'];
$town = $_POST['town'];
$compname = $_POST['compname'];
$compreg = $_POST['compreg'];
$verify = $_POST['verify'];
$verification = $_POST['verification'];
$firstname = stripslashes($firstname);
$firstname = mysql_real_escape_string($firstname);
$lastname = stripslashes($lastname);
$lastname = mysql_real_escape_string($lastname);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$email2 = stripslashes($email2);
$email2 = mysql_real_escape_string($email2);
$contactnum = stripslashes($contactnum);
$contactnum = mysql_real_escape_string($contactnum);
$mobnum = stripslashes($mobnum);
$mobnum = mysql_real_escape_string($mobnum);
$postcode = stripslashes($postcode);
$postcode = mysql_real_escape_string($postcode);
$addres1 = stripslashes($addres1);
$addres1 = mysql_real_escape_string($addres1);
$addres2 = stripslashes($addres2);
$addres2 = mysql_real_escape_string($addres2);
$town = stripslashes($town);
$town = mysql_real_escape_string($town);
$compname = stripslashes($compname);
$compname = mysql_real_escape_string($compname);
$compreg = stripslashes($compreg);
$compreg = mysql_real_escape_string($compreg);
$verify = stripslashes($verify);
$verify = mysql_real_escape_string($verify);
$verification = stripslashes($verification);
$verification = mysql_real_escape_string($verification);
$query = sprintf("SELECT * FROM supplier_registration WHERE supplier_email='%s'", mysql_real_escape_string($email2));
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
$_SESSION['message2'] = '<div id="message_box3"><div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"></div><h23>Found You!</h23><p>It appears that a user with that email address is already registered. Please Login below or click on our support section.</p> </div>';
header('Location: ../login.php');
} else {
$sql = "INSERT INTO supplier_registration (id, first_name, last_name, supplier_email, contact_number, mobile_number, postcode, address1, address2, town, company_name, company_reg, date) VALUES (NULL, '$firstname','$lastname','$email2', '$contactnum', '$mobnum', '$postcode', NULL, NULL, NULL, '$compname', '$compreg', now())";
$result2 = mysql_query($sql);
if(mysql_num_rows($result2) > 0) {
$_SESSION['message2'] = '<div id="message_box3"><div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"></div><h23>Thanks for Registering!</h23><p>You have successfully registered. We have sent you a verification email.</p> </div>';
header('Location: ../index.php');
}else{
$_SESSION['message2'] = '<div id="message_box3"><div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"></div><h23>Oooops!</h23><p>It appears there was an error whilst attempting to register your details. Please try again later.</p> </div>';
header('Location: ' . $_SERVER['HTTP_REFERER']);
} }
?>
The error may relate to the datatypes of the fields in your table.
In your code there is no conversion of strings to numbers.
If you add the table definition and the exact SQL error to your question more help can be given.
try this..
$sql = "INSERT INTO supplier_registration (id, first_name, last_name, supplier_email, contact_number, mobile_number, postcode, address1, address2, town, company_name, company_reg, date) VALUES ('', '$firstname','$lastname','$email2', '$contactnum', '$mobnum', '$postcode', '', '', '', '$compname', '$compreg', now())";
$result2 = mysql_query($sql);
It's because date in your query is a Reserved Keyword. so you'll have to put in [] like this [date]

PDO Update Multiple Rows

Bit of a noob when it comes to PDO. We have a a table that needs to be updated with a cron job daily. The idea is to query the table and for each "active = 1" get an integer from a duration column convert that into days, get the "expiration" column and the duration to the expiration and update the expiration.
I am not even close to getting this to work, I am trying to just get the basics for now. Return the duration which is in hours divide by 24 add that to the date column as days and update EACH row with the appropriate new time.
The problem is I do not know how to update each row with its own information. I have the code below, it updates each row but the new "expires" date ends up being the same even though the expires values are different.
static function cronSetFeatured(){
try{
$db = new PDO('mysql:host=127.0.0.1;dbname=mydb', 'dbuser', 'pw' );
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo $e->getMessage();
die();
}
$query = $db->query('SELECT * FROM featured_producers ');
$now = date('Y-m-d H:i:s');
while($r = $query->fetch(PDO::FETCH_OBJ)){
$duration = $r->duration;
$ddays = $duration / 24;
$date = $r->date;
$expires = date("Y-m-d", strtotime($date. " + ".$ddays." days"));
}
$sql = "UPDATE `featured_producers`
SET `expires`= ?
WHERE `id` != 0";
$q = $db->prepare($sql);
$q->execute(array($expires));
echo $expires.'<br>';
}
Well if you want to UPDATE each record on its own, that query need to be part of the loop body:
while($r = $query->fetch(PDO::FETCH_OBJ)){
//calculate expiration
$duration = $r->duration;
$ddays = $duration / 24;
$date = $r->date;
$expires = date("Y-m-d", strtotime($date. " + ".$ddays." days"));
//Get the id (needed for update)
$id = $r->id;
//updating
$sql = "UPDATE `featured_producers`
SET `expires`= ?
WHERE `id` != ?";
$q = $db->prepare($sql);
$q->execute(array($expires, $id));
echo $expires.'<br>';
}

Get only today posts?

i need to have a function that will echo the post that has been posted today.
from 00.00 to 23.59 . ihave created a function but it is not giving the result i need
here is my function:
function todayNews() {
$id = mysql_real_escape_string ($id);
$sql = 'SELECT * FROM wp_posts WHERE post_status = "publish" AND post_date = CURRENT_DATE ORDER BY post_date DESC LIMIT 15';
$res = mysql_query($sql) or die (mysql_error());
if (mysql_num_rows($res) !=0):
while ($row = mysql_fetch_assoc($res)) {
$title = ($row['post_title']);
$old_date = $row['post_date']; // returns Saturday, January 30 10 02:06:34
$old_date_timestamp = strtotime($old_date);
$new_date = date('H:i', $old_date_timestamp);
$mycontent = ($row['post_content']);
$mycontent = strip_tags($mycontent);
$mycontent = substr($mycontent,0,350);
$mycontent = preg_replace("/\[caption.*\[\/caption\]/", '', $mycontent);
$first_img = '';
$my1content = $row['post_content'];
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $my1content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/img/default.png";
}
echo '
<ul class="li-sub">
<li>
'.$title.'
</li>
</ul>
';
}
else:
echo 'There are no posts for today !';
endif;
} // end
Thank you !
EDIT:
Post_date have this format : Y-m-d H:i
You are comparing POST_DATE which is a datetime with CURRENT_DATE which is a Date , it won't give any result.
you can try the following SQL
$sql = 'SELECT * FROM wp_posts WHERE post_status = "publish" AND DATE(post_date) = CURRENT_DATE ORDER BY post_date DESC LIMIT 15';
This will convert the post_date to only date before comparing with current date.