Basic SQL Update statement not working in PHP - 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

Related

How to add string value to cell in SQL using php?

I am trying to update varchar cell in SQL users table. Now the value of groups_id is 3. $last_id = 4. I want to change it to 3, 4. Could you please tell me what I am doing wrong?
With this code the value remains the same
$sql = "UPDATE registration.users SET groups_id = groups_id+', $last_id' WHERE username = '$user_name'";
$update_groups_id = $db->query($sql);
$val = $groups_id . ", ".$last_id;
$sql = "UPDATE registration.users SET `groups_id` = '$val' WHERE username = '$user_name'";
$update_groups_id = $db->query($sql);
your SQL query is wrong, you are not concatenating variables properly, try doing this way, I think it should help you
There is a syntax fault in your $sql object as you use +', $last_id'. If you want to append in PHP you can use . in string context
Also I'm pretty sure you can leave the '' from the variables so '$last_id' will become $last_id
But more important is that you do not check for any security issues. I hope $user_name and $last_id are not just taken from the input as SQL injections are possible.
I recommend you to look at mysqli_prepare and mysqli_bind

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.

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."' " );

Textareas with dynamically-assigned name throws my code

I have a number of textareas, each with a unique assigned name (name="adcode$ID", for example). When I try to pass those names to the code below, it doesn't work because of the dynamic part.
if (isset($_POST['editadapp'])) { // Edit AD
$newadcode = mysql_real_escape_string($_POST['.adcode$ID.']);
$doedit = "UPDATE ads SET adcode = '".$newadcode."') WHERE ads_ID=$ID" or die(mysql_error());
$updatead = mysql_query($doedit) or die(mysql_error());
header("Location: " . $_SERVER['PHP_SELF']);
How can I resolve this?
There is so much wrong with this that it's frightening.
Firstly,
$doedit = "UPDATE ads SET adcode = '".$newadcode."') WHERE ads_ID=$ID" or die(mysql_error());
That code snippet is wrong on many levels.
The sql syntax is wrong
The sql is formatted with strings from user input (see parameterization of queries here
or die() should not be used here, you're creating a string
Ideally you should have code like:
$dbh = new PDO('connectionstring to connect to your database');
$sql = 'update ads set adcode = ? where ads_id = ?';
$sth = $dbh->prepare($sql);
$sth->execute(array($_POST['adcode' . $ID], $ID));
Other topics:
Are Paramerterized queries necessary in pdo?
prepared queries with pdo
Preventing sql injection in php
You seem to be attempting string concatenation. Here's how to do that correctly:
$newadcode = mysql_real_escape_string($_POST['adcode' . $ID]);
The following line should simply create a string containing your SQL query; you don't execute it until the next line, there is no function call so the or die is out of place. You also mix concatenation with interpolation (variable names within a double quoted string) which is fine but probably not helping you understand your syntax issues, so let's be consistent:
$doedit = "UPDATE ads SET adcode = '" . $newadcode . "' WHERE ads_ID = " . $ID;
you should use array like adcode[<?php echo $ID;?>] at your page where the text area is and a hidden field name=adID[$ID]. At the page where the query executes
$adID = $_POST['adID'];
$newadcode = mysql_real_escape_string($_POST['adcode']);
$N = count($adID);
for($i=0;$N<$i;$i++){
$doedit = mysql_query("UPDATE ads SET adcode = '$newadcode[$i]' WHERE ads_ID=$adID[$i];") or die(mysql_error());

PDO - passing a field name as a variable

I'm just migrating my code from mysql_query style commands to PDO style and I ran into a problem. THe old code looked like this :
$query_list_menu = "SELECT ".$_GET['section_name']." from myl_menu_hide_show WHERE id='".$_GET['id']."'";
And the updated code looks like below. Apparently it's not working. I store in $_GET['section_name'] a string that represents a field name from the database. But I think there is a problem when I pass it as a variable. Is the below code valid ? Thanks.
$query_list_menu = "SELECT :section_name from myl_menu_hide_show WHERE id=:id";
$result_list_menu = $db->prepare($query_list_menu);
$result_list_menu->bindValue(':section_name', $_GET['section_name'] , PDO::PARAM_STR);
$result_list_menu->bindValue(':id', $_GET['id'] , PDO::PARAM_INT);
$result_list_menu->execute();
If $_GET['section_name'] contains a column name, your query should be:
$query_list_menu = "SELECT " . $_GET['section_name'] . " from myl_menu_hide_show WHERE id=:id";
Giving:
$query_list_menu = "SELECT :section_name from myl_menu_hide_show WHERE id=:id";
$result_list_menu = $db->prepare($query_list_menu);
$result_list_menu->bindValue(':id', $_GET['id'] , PDO::PARAM_INT);
$result_list_menu->execute();
The reason is that you want the actual name of the column to be in the query - you'd changed it to be a parameter, which doesn't really make much sense.
I'll also add that using $_GET['section_name'] directly like this is a massive security risk as it allows for SQL injection. I suggest that you validate the value of $_GET['section_name'] by checking it against a list of columns before building and executing the query.
There is no good and safe way to select just one field from the record based on the user's choice. The most sensible solution would be to select the whole row and then return the only field requested
$sql = "SELECT * from myl_menu_hide_show WHERE id=?";
$stmt = $db->prepare($query_list_menu);
$stmt->execute([$_GET['id']]);
$row = $stmt->fetch();
return $row[$_GET['section_name']] ?? false;

Categories