How do I update MySQL row in PHP? - php

I have a MySQL database that I'm working with, but when I try to update a row in it, it doesn't work. Here's the update code I'm working with:
mysql_query("UPDATE offtopic SET next = '$insert' WHERE id = '$id'");

First of all, you should make it a bit more safe:
mysql_query(sprintf("UPDATE offtopic SET next = '%s' WHERE id = '%s'",
mysql_real_escape_string($insert),
mysql_real_escape_string($id));
Now, is your id actually string, and not numeric? If its numeric, you should rather have:
mysql_query(sprintf("UPDATE offtopic SET next = '%s' WHERE id = %d",
mysql_real_escape_string($insert), $id);

your syntax is correct, so it might be an error with the variables or your field names.
Try this:
$sql = "UPDATE offtopic SET next = '$insert' WHERE id = '$id'";
if (!mysql_query($sql)) {
echo "MySQL Error: " . mysql_error() . "<br />" . $sql;
}
That might show you some useful information to help you debug.

Please, for the love of the internet, don't built an SQL query yourself. Use PDO.

Related

Basic SQL Update statement not working in PHP

I'm working on a simple, small project for a class - a mock-database (built using phpMyAdmin) with an accompanying web application for user input, to allow for searching/appending/updating said database. Searching and Appending is working perfectly, but updating is giving me grief.
I have error messages set to display to help in the debugging process, and although they've popped up for previous issues in this project, they haven't shown up for this particular problem.
My code looks like this:
$sth = "UPDATE adjunct_number
SET FIRSTNAME = '.$updateInformation.'
WHERE 700NUMBER = '.$updateCriteria.';";
(I tried echoing $sth right here, nothing displayed!)
$sth = $db->prepare($sth);
$sth->execute();
$updateInformation and $updateCriteria are both being pulled from an HTML form's text boxes successfully. (I'll enter Drew and 700123456 into the form as test data.) I tested that $updateInformation and $updateCriteria ARE in fact being successfully captured using this statement:
echo $updateInformation . ", " . $updateCriteria
Which yields the following output:
Drew, 700123456
I'll enter the following query into phpMyAdmin to test it first.
UPDATE adjunct_number
SET FIRSTNAME = 'DREW'
WHERE 700NUMBER = 700482306
It always works in phpMyAdmin, as expected, 100% of the time... however, the exact same update command never works when I send it through via PHP, which confusions me greatly. The only thing I can think of is an overlooked PHP typo in my SQl statement, but at this point in time I've been staring at it for so long that I could use a fresh set of eyes! Why is it that when I tried to echo $sth, no sql statement was displayed? Any insight from this wonderful community would be greatly appreciated.
You need to learn basic PHP strings:
$sth = "UPDATE adjunct_number
^---start of PHP string
SET FIRSTNAME = '.$updateInformation.'
WHERE 700NUMBER = '.$updateCriteria.';";
^---end of PHP string
That means your query is doing ... SET FIRSTNAME = '.foo.' ..., with the . embedded literally within the query. That means your where clause will never match any records.
Since you're using " for the quotes, you don't NEED to use the . at all:
$sth = "UPDATE adjunct_number
SET FIRSTNAME = '$updateInformation'
WHERE 700NUMBER = '$updateCriteria';";
or you should properly exit the string first:
$sth = "UPDATE adjunct_number
SET FIRSTNAME = '" . $updateInformation . "'
WHERE 700NUMBER = '" . $updateCriteria . "';";
No need of ; in your query. You are not in interactive session
You are subject to SQL injection.
No need of quote with parameterized query.
Here's a suggestion how you you could do it.
$query = "UPDATE adjunct_number SET FIRSTNAME = ? WHERE 700NUMBER = ?";
$sth = $db->prepare($query);
$sth->execute( array( $updateInformation, $updateCriteria ) );
You have mixed single and double quotes. Update it to the following:
$sth = "UPDATE adjunct_number
SET FIRSTNAME = ".$updateInformation."
WHERE 700NUMBER = ".$updateCriteria.";
May be you can try using the symbol (" ` ")backtick for column names and tables
UPDATE `adjunct_number`
SET `FIRSTNAME` = 'DREW'
WHERE `700NUMBER` = 700482306

My PHP SQL query is throwing errors, even though it works in the SQL console

I'm trying to create a function for my forum that will increment my user's "Posts" attribute by 1. For whatever reason, the following PHP does not work.
function postCountIncrease($username) {
//get the connection variable
global $con;
//change to the users database (this function works correctly)
sqlconnect_users();
//get current post number (this is also working)
$getCurrentPosts = "SELECT Posts\n"
. "FROM users\n"
. "WHERE Username='".$username."'";
$query1 = mysqli_query($con, $getCurrentPosts) or die(mysqli_error($con));
$currentPosts = mysqli_fetch_array($query1);
//here is the problematic post. Assume that $username is a valid value, and that I've already done mysqli_real_escape_string() on it
$incrementPostsQuery = "UPDATE users.users SET Posts=". $currentPosts[0]+1 ." WHERE Username='". $username ."'";
$query2 = mysqli_query($con, $incrementPostsQuery) or die(mysqli_error($con));
//return the result
$result = mysqli_fetch_array($query2);
return $result;
}
I honestly don't see what I'm doing wrong, because the SQL works fine. If I use UPDATE users.users SET Posts=1 WHERE Username='Lampitosgames' in the console, it works with no errors. Help is much appriciated. Also, here is the error it is throwing at me:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1 WHERE Username='Lampitosgames''
You can not concatenate that way "toto ".$var+1, you have to surround with brackets "toto ".($var+1)
In your case, this is declaration of var $incrementPostsQuery which fails
Look at your errors, your syntax is off
$getCurrentPosts = "SELECT Posts
FROM users
WHERE Username='$username'";
The error is in the building of your query.
$incrementPostsQuery = "UPDATE users.users SET Posts=". $currentPosts[0]+1 ." WHERE Username='". $username ."'";
I'll suggest you some tips to create query like this:
"update table set field = value"; // you can write the value directly
"update table set field = ". $value; // easy
"update table set field = ". ($a+$b); // ...
"update table set field = {$value}"; // you can add a variable with curly braces
"update table set field = {$va[3]}"; // more compless way
"update table set field = {$a->b}"; // an object field

PHP: Update database table

I'm trying to get this to update the messages table in my database, and set the message_read cell to 1.
But I can't get it to work. It always says 0 where it supposed to change to 1.
I'm pretty sure the variables are right.
$q = "UPDATE messages SET message_read='1' WHERE id='$messageid' AND to_user='$usermsg'";
mysql_query($q);
I do not get any errors either.
"usermsg" = the session username
"messageid" = the id of the message
Try this:
$q = "UPDATE messages SET message_read='1' WHERE id=".mysql_real_escape_string($messageid)." AND to_user='".mysql_real_escape_string($usermsg)."';";
$result = mysql_query($q);
if(!$result)
{
die( mysql_error() );
}
else
{
echo 'Number of affected rows:'.mysql_affected_rows();
}
If there was something wrong with your query you will be able to see the error printed on screen. And if not you can see how many rows were affected by the query.
I've also added some SQL injection projection just in case.
I think this is the correct syntax:
$q = "UPDATE messages SET message_read = 1 WHERE id = ".$messageid." AND to_user='".$usermsg."'";
Don't use quotes when the field type is INT.

SQL error in php

Hey, I wrote some code for extracting some information out of the database and checking to see if it met the $_COOKIE data. But I am getting the error message:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
My code so far is:
$con = mysql_connect("XXXX","XXXXX","XXXXXXX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("XXXXXX", $con);
$id = $_COOKIE['id'];
$ends = $_COOKIE['ends'];
$userid = strtolower($_SESSION['username']);
$queryString = $_GET['information_from_http_address'];
$query = "SELECT * FROM XXXXX";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
if ($queryString == $row["orderid"]){
$sql="UPDATE members SET orderid = ''WHERE (id = $id)";
$sql="UPDATE members SET level = 'X'WHERE (id = $id)";
$sql="UPDATE members SET payment = 'XXXX'WHERE (id = $id)";
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
}
}
Any help would be appreciated,
Thanks.
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
should be
$sql="UPDATE members SET ends = '$ends'WHERE (id = '$id')";
(IE add the ' around $id)
I'm not sure if this is the error, but do you realize you're code only runs the last UPDATE? You're assigning $sql 4 time, and only running it after the fourth assignement...
If $_COOKIE['id'] does not have a value, then $id in your SQL statements will be blank, leaving your SQL looking like this:
UPDATE members SET ends = 'something' WHERE (id = )
which, of course, is invalid SQL.
Only one of the SQL statements will execute, and that's the last one. You need to add some whitespace before the WHERE clause, like this:
$sql="UPDATE members SET ends = '$ends' WHERE (id = $id)";
Also be wary of SQL injection attacks in the event that your cookie is altered by the end user. One other thing of note is your orderid column. Is it a VARCHAR or some other unique identifier? If it's an integer, then setting it to empty string will not work. You might want to rethink your schema a bit here.
EDIT: Another thing you need to do is check to make sure the cookies actually have values. If not, your SQL strings will be messed up. Have you though about using parameterized queries through PDO so you don't have to worry about SQL injection at all?
first of all you keep overwriting $sql variable so only the
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
is being executed.
And I would say that $id variable is not what you think it is (maybe empty as query like the one above without id:
$sql="UPDATE members SET ends = '$ends'WHERE (id = )";
would throw such error back.
Try
$id = NULL;
before
$id = $_COOKIE['id'];
if the error is gone that means that $id is not what you think it is

Updating SQL database using PHP

I am trying to make a password retrieval system on my site, and I am having problems updating the password reset field in my database. I have tried everything, but nothing seems to work.
This is my code so far:
$passwordreset = md5(mt_rand()) . md5(mt_rand()) . md5(mt_rand());
$con = mysql_connect("localhost","XXX","XXX");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
mysql_query("UPDATE members SET passwordreset = $passwordreset WHERE id = $id");
When I try to insert the data I get the error:
Error: Query was empty
Any help would be appreciated,
Thanks.
Not sure it's the only problem, but I'm guessing your passwordreset field is a string, in the database -- to store a concatenation of several md5, which are strings, it has to.
So, there should be quotes arround the value you put in this field, in the SQL query :
mysql_query("UPDATE members SET passwordreset = '$passwordreset' WHERE id = $id");
And, in a general case, you should escape your string values with mysql_real_escape_string :
mysql_query("UPDATE members SET passwordreset = '"
. mysql_real_escape_string($passwordreset)
. "' WHERE id = $id");
It won't change anything here, as there is no quote in a md5... But it's a good practice to always do it, to never find yourself in a situation where it was necessary and you didn't do it.
I am not sure, if you get an empty query error for this, but you need ticks around the values:
mysql_query("UPDATE members SET passwordreset = '$passwordreset' WHERE id = '$id'");
I guess the backticks around the names of the columns are missing, try:
mysql_query("UPDATE members SET `passwordreset` = '$passwordreset' WHERE `id` = '$id'");
Are the two line breaks after $passwordreset intentional? Can you try removing them?

Categories