Why can't I Update mysql table? - php

My sql table is not updating. I have looked through tons of documentation and I do not see why it is not working.
if (!empty($_POST['services'])){
$username = mysql_real_escape_string($_POST['username']);
$service = mysql_real_escape_string($_POST['services']);
$registerquery = mysql_query("UPDATE users SET service = '".$service."' WHERE Username = '".username."'");
}

Please update your code to use PDO. Inserting into the database could be much easier and safer using prepared statements.
For example:
<?php
$stmt = $db->prepare("UPDATE `users` SET `services`=:service WHERE `username`=:username");
$stmt->execute(array(':username' => $username, ':service' => $service));
?>
Here's a good resource when learning the basics of PDO.
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Have a good one!
- Scott

My error was that I wrote this: $registerquery = mysql_query("UPDATE users SET service = '".$service."' WHERE Username = '".username."'"); and I was missing the $ and an s in services. To correct this: $registerquery = mysql_query("UPDATE users SET services = '".$service."' WHERE Username = '".$username."'"); Thank you all for your help. I submitted another answer last night saying I found the error.

I have tried to close this twice. All I had to do was add a "s" at the end of "service" in the update command. I overlooked the fact it did not match the requested field in the table.

Please replace like this and execute.
$registerquery = mysql_query("UPDATE users SET service = '".$service."' WHERE Username = '".$username."'");

Related

Query works in MySQL but I get 'Query was empty' in PHP

The code below is part of a simple password manager. I get an error saying the Query is empty yet the query works just fine in MySQL. (The 1 and the test value were originally variables I just changed them to values as part of my troubleshooting). I am also aware that the column names user and password may be problematic, but I added ` around them. What else could be wrong with that code?
$change_pass_query = "UPDATE `user` SET `password` = PASSWORD('test') WHERE id = 1";
$change_pass_result = mysql_query($change_pass_query) or die('Error. Change Password Query failed: '. mysql_error());
Try formatting your SQL like this:
UPDATE `user` SET `password` = 'test' WHERE `id` = 1
http://php.net/manual/en/function.mysql-query.php
Notice the warning at the top of that page. Nobody uses mysql_query or any plain mysql functions. Research mysqli/mysqli_query, and PDO.
Here's how you could do this with PDO:
$pdo = new PDO("mysql:host=localhost;dbname=mydb","username","password");
$stmt = $pdo->prepare("UPDATE `user` SET `password` = PASSWORD(:password) WHERE id = :id");
$result = $stmt->execute(array(':password' => "test",':id' => 1));
if (!$result) die('Error. Change Password Query failed: '. mysql_error());
Here's some documentation on PDO: http://php.net/manual/en/book.pdo.php
I ended up renaming all tables and fields so that I didn't use any reserved words, as I thought that the issue might be that. The problem still happened. I then copied my code to a different PHP box, et voila, the code works just fine. I'll have to put it down to an issue with the PHP version/installation on the older box and move on. There is nothing wrong with the code.

Trouble with MYSQL update column for one selection

I'm having trouble getting this to update when needed. This is an optout script intended to updated the selected email row with the value of 1 in the removed column. I can't seem to get it to update and I'm thinking its an issue with my sql. Any help in understanding this is much appreciated.
As a note:
I'm making it to Sorry there seems to be an issue with.........
Here is the script.
<?php
if (isset($_GET['e'])) {
include_once "../storescripts/connect_to_mysql.php";
$email = $_GET['e'];
$sql_delete = mysql_query("UPDATE test WHERE email='$email' SET removed = '1'");
if (!$sql_delete) {
echo "Sorry there seems to be and issue when trying to remove your listing. Please email Admin directly using this email address: chris#.com";
} else {
echo "Sorry to see you go! You will not receive our newsletter ever again unless you relist. To gain access to our newsletter again simply let us know by email at chris#.com";
}
}
?>
Try:
$sql_delete = mysql_query("UPDATE test SET removed = '1' WHERE email='$email'");
The problem is your syntax, have a look at the mysql update syntax, where the where clause should go and where set should go http://dev.mysql.com/doc/refman/5.0/en/update.html.
You would have seen this problem had you used proper error handling, like follows:
$sql_delete = mysql_query("UPDATE test SET removed = '1' WHERE email='$email'") or die(mysql_error());
Have a look at mysql_real_escape_string http://www.php.net/manual/en/function.mysql-real-escape-string.php, to prevent SQL injection. Example:
$email = mysql_real_escape_string($email);
$sql_delete = mysql_query("UPDATE test SET removed = '1' WHERE email='$email'") or die(mysql_error());
Also note that mysql_ extension are deprecated, you want to start using mysqli or PDO.
Use SET before your WHERE clause.
UPDATE test
SET removed = '1'
WHERE email = '$email'
The update syntax is
UPDATE
table
SET
column = value
WHERE
condition = met
On another note, I see you're using a very unsafe method of dynamic entries ($_GET) and Mysql_* function are deprecated in new version of php >= 5.5. I'd highly recommend researching PDO for the use of bind variables otherwise you can easily get "hacked" if
$_GET['e'] = "fake' OR '1'='1" // known as sql injection
Good Read
How to prevent SQL injection in PHP?
Why shouldn't I use mysql_* functions in PHP?
You are right, your UPDATE syntax is incorrect. This is the correct form:
UPDATE test
SET removed = '1'
WHERE email = '$email'
Your query should be
mysql_query("UPDATE test SET removed = '1' WHERE email='$email'");
But please notice that this extension is deprecated.
Use MySQLi or PDO_MySQ instead.
the solution in both extensions are as follows.
MySQLi:
$mysqli = new mysqli(GDB_HOST, GDB_USERNAME, GDB_PASSWORD, GDB_NAME);
$cmd = $mysqli->prepare("UPDATE test SET removed = '1' WHERE email= ? ");
$cmd->bind_param('s', $email);
$cmd->execute();
PDO
$dbh = Database::connect();
$query = "UPDATE test SET removed = '1' WHERE email= ? ";
$sth = $dbh->prepare($query);
$sth->execute(array($email));
One of the big importances of using one of these 2 extensions is the fact that you avoid any attempt of SQL injection

Php update function

I wrote this code
if(isset($_POST['update'])) {
$webname = $_POST['webname'];
$webmeta = $_POST['webmeta'];
$webdesc = $_POST['webdesc'];
$sql=("UPDATE settings (name, meta, description) VALUES ('$webname', '$webmeta', '$webdesc')");
}
but the problem is that it doesn't update my database, and I cannot find anything wrong in the code ...
I have name "update" on submit button, and all my fields are the same as in code
That's insert! Not update!
$sql=("UPDATE `settings` SET `name` = '$webname',
`meta` = '$webmeta',
`description` = '$webdesc')
WHERE [some condition]");
And replace the [some condition] with a valid condition.
Your code is heavily vulnerable to SQL Injection.
Consider escaping the input by replacing these:
$webname = $_POST['webname'];
$webmeta = $_POST['webmeta'];
$webdesc = $_POST['webdesc'];
With:
$webname = mysql_real_escape_string($_POST['webname']);
$webmeta = mysql_real_escape_string($_POST['webmeta']);
$webdesc = mysql_real_escape_string($_POST['webdesc']);
Or something equivalent like PDO or MySQLi.
mysql_select_db("my_db", $con);
mysql_query("UPDATE Persons SET Age=36
WHERE FirstName='Peter' AND LastName='Griffin'");
u need to first formulate query ans then run/ execute that
$query = "UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value";
// Perform Query
$result = mysql_query($query);
You need to run
$connection = mysql_connect($server, $serv_Username, $serv_Password);
mysql_select_db($dbase_name, $connection);
mysql_query($update_query, $connection));
I don't know if this is your problem (don't know how much you know about PHP so just saying).
Also your syntax is wrong. Should be:
UPDATE tablename SET column_name='some_value' WHERE column_name ='some_value'
note that this is diffrent from mentioned above without the thingys covering the column_name parameters.
better is to use PDO as mentioned above, mysql_ can be used "safely" on < PHP 5.5.
Try The code shown below
Just replace the field names and values with your information on your database
$editid=$_POST['editid'];
$username=callback($_POST['username']);
$password=callback($_POST['password']);
$name=callback($_POST['name']);
$age=callback($_POST['age']);
$phone=callback($_POST['phone']);
$emailaddress=callback($_POST['emailaddress']);
$gender=callback($_POST['gender']);
$description=callback($_POST['description']);
$update=update("users","username='".$username."',password='".$password."',name='".$name."',age='".$age."',phone='".$phone."',emailaddress='".$emailaddress."',gender='".$gender."',description='".$description."' ","ID='".$editid."' " );

IF and ELSE statement not working

I am trying to award a user a badge if their points are 10,000. There is a field in the table called badge1 with a default value set to locked and a points row. I am running and if statement that if the users points are 10,000 then UPDATE the badge1 row from locked to unlocked. My code seems correct but It is neither updating the the field nor showing any errors.
<?php
$db = new PDO('mysql:host=hostname;dbname=databasename;charset=UTF-8', 'username', 'password');
$username = $_SESSION['username'];
$q = "SELECT Points FROM login_users WHERE username ='$username'");
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Points = $row['Points'];
if($Points == "10000") {
$awardBadge = $db->exec("UPDATE login_users SET badge1=unlocked WHERE username=?");
$Points->execute(array($username))
} else {
print "";
}
?>
UPDATE:
I managed to get it working.. however the problem is I am a bit new to converting old sql to PDO so this is not very secure but this is what works:
<?php
$connect = mysql_connect("host","username","password");
mysql_select_db("databasename");
$username = $_SESSION['jigowatt']['username'];
$q = "SELECT Points FROM login_users WHERE username = ('$username')";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Points = $row['Points'];
?>
// Place somewhere
<?php
if($Points >= "10000") {
$result = mysql_query("UPDATE login_users SET maneki='unlocked' WHERE username='$username'");
} else {
print "Badge has not been unlocked";
}
?>
"10000" string should be an 10000 int
And also, you might want to make a choice here too. You're using 2 types of setting up a mysql-database connection. the old-fashioned mysql_function() way and the new fancy PDO method.
I think working with the PDO version is safer, since newer PHP versions will not support the old methods anymore... That... and it just looks dirty ;P
Try this:
<?php
session_start();
$dbSession = new PDO('mysql:host=***;dbname=***', '***', '***');
$selectQuery = $dbSession->prepare('
SELECT `User`.`Points`
FROM `login_users` AS `User`
WHERE `User`.`username` = :username
');
$selectQuery->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
$user = $selectQuery->fetch(PDO::FETCH_ASSOC);
if ( !empty($user) && $user['Points'] == 10000 ) {
$updateQuery = $dbSession->prepare('
UPDATE `login_users`
SET `badge1` = \'unlocked\'
WHERE `username` = :username');
$updateQuery->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
$updateQuery->execute();
}
?>
Usefull resources:
PHP Database Objects (PDO)
PHP Sessions
MySQL Datamanipulation
MySQL SELECT syntax
MySQL UPDATE syntax
Better check if >= 10000 and not yet awarded. That could you also be done in SQL so you don't need that logic in PHP.
UPDATE login_users SET badge1=unlocked WHERE points >= 10000 and badget1 <> unlocked
The issue is caused by $point value which actually is not equal to 10000, but is NULL.
So I propose to always use var_dump() to get the actual value of the variable in such cases.
one tip: check the PDO docs, before you write php code! You use PDO and mysql commands on same time for same job!?? why???
Try this if($Points == 10000) instead of if($Points == "10000")
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.
if($Points==10000){
$awardBadge = $db->prepare("UPDATE login_users SET badge1=unlocked WHERE username=?");
$awardBadge->execute(array($username));
}

Unable to figure out syntactical error in MySQL statement

I know this is a short question but i can't figure out the syntactical error in this line:
$insert = mysql_query("UPDATE user SET userName = '$username_change' WHERE userID = '$_SESSION['userid']' ");
I know the problem is with $_SESSION variable but don't what, if anything, i need to escape or alter for the statement to work.
Try wrapping your array variables within curly brackets:
UPDATE user SET userName = '$username_change' WHERE userID =
'{$_SESSION['userid']}'
Also think about moving away from the mysql_* functions.
try:
$insert = mysql_query("UPDATE user SET userName = '".$username_change."' WHERE userID = ".$_SESSION['userid']);
Try this
UPDATE user SET userName = '$username_change' WHERE userID = "'.$_SESSION['userid']."' "

Categories