Trying to update an entry in a database - php

I'm trying to update a record in my database using the code below. I'm trying to change the product name but I am getting the following error:
Could not update data: Unknown column 'Earrings' in 'field list'
Code:
<?php
if(isset($_POST['update']))
{
$dbhost = 'databasehost';
$dbuser = 'username';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$ProductsID = $_POST['ProductsID'];
$ProductsName = $_POST['ProductsName'];
$sql = "UPDATE Products ".
"SET ProductsName = $ProductsName ".
"WHERE ProductsID = $ProductsID" ;
mysql_select_db('databasename');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
else
{
?>

The query should be
$sql = "UPDATE Products ".
"SET ProductsName = '$ProductsName' ".
"WHERE ProductsID = $ProductsID" ;
You forgot to wrap $ProductName with quotations. Don't forget to do so when dealing with string values.

You want something like this:
ProductsName = '$ProductsName'
Also, be sure to escape that input, else you'll be subjected to SQL injections.

Your are trying to set the ProductsName to an existing column, add quotes to let sql interpret a value:
$sql = "UPDATE Products ".
"SET ProductsName = '$ProductsName' ".
"WHERE ProductsID = $ProductsID" ;

You are not sanitizing your data, so there is a good chance that your query could break depending on the value submitted, not to mention it leaves your database wide open for an attacker to manipulate via SQL Injection.
Please do not use mysql_ functions, as they are depricated. You should be using prepared statements, please see PDO and mysqli.
As for your answer, you need to put 'quotes' around the $variable

Related

Parse a url and return database rows [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
I'm trying to parse a url and connect to a database.
For instance when a user visits url.php?id=1 they should get a list of questions and answers related to that topic.
When I run the MySQL query
SELECT * FROM QuestionDB WHERE TopicID = 1
In phpmyadmin I get the desired rows.
Here is my code. I returns a blank document!
$topic = $_GET['id'];
$dbhost = 'host';
$dbuser = 'user';
$dbpass = 'pass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM QuestionDB WHERE TopicID = '$topic'';
mysql_select_db('mydb');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "Question :{$row['Question']} <br> ".
"Answer : {$row['Answer']} <br> ".
"Author : {$row['Author']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
I can't work out what I'm doing wrong. If I delete the WHERE TopicID = '$topic' portion of my query, this code does print out all the rows from my database.
Cheers in advance
You have a syntax error. The string concatenation with the variable fails.
You have to change this line :
$sql = 'SELECT * FROM QuestionDB WHERE TopicID = "'.$topic.'"';
or
$sql = "SELECT * FROM QuestionDB WHERE TopicID = '$topic'" ;
Important note : Your code is vulnerable to SQL injections and may compromise the security of your database. You should use PDO or mysqli APIs to secure your SQL queries, and using prepare function.

PHP - Entering data into a database [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I've recently trying to add data into a database, (New to php), I've looked over to see where I've gone wrong, but can't find anything. The error is:
Unknown column 'FUMUKU' in 'field list'
Code:
$dbhost = 'localhost';
$dbuser = 'evocityi_admin';
$dbpass = 'password';
$database = 'evocityi_stocks';
$conn = mysql_connect($dbhost, $dbuser, $dbpass, $database);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$Dtime = "30/04/16";
$StockName = "FUMUKU";
$FUMUKUPrice = 1000;
$sql = "INSERT INTO stocks".
"(Stock,Price, TimeD) ".
"VALUES ".
"('$StockName,$FUMUKUPrice, $DTime')";
mysql_select_db('evocityi_stocks');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
SQL Database:
https://gyazo.com/fc97b686cfea79ea773d1796e912551e
Use this It will helps you.
$sql = "INSERT INTO stocks(Stock,Price,TimeD) VALUES ('$StockName','$FUMUKUPrice', '".date('Y-m-d',strtotime($Dtime))."')";
'$StockName,$FUMUKUPrice, $DTime'
You should surround every variable with quotes:
'$StockName' ,' $FUMUKUPrice' , '$DTime'
Just know that when blindly concatenating variables into a SQL query and not preparing statements for user input makes your code vulnerable to SQL injection. Use Prepared Statements instead. Also, use the mysqli_* functions, the mysql_* functions are deprecated.
Try this query, you are not using qoutes properly on the variables due to this It through error.
$sql = "INSERT INTO stocks".
"(Stock,Price, TimeD) ".
"VALUES ".
"('".$StockName."', '".$FUMUKUPrice."', '".$DTime."')";
To avoid deprecation and SQL Injection you should use PDO or mysqli.
You're using mysql_* functions, that's what's wrong.
Read the documentation and look into alternatives.
One such alternative may be:
$query = $pdoconnection->prepare("
insert into `stocks`
(`Stock`,`Price`,`TimeD`)
values (?,?,?)
");
$query->execute([$StockName, $FUMUKUPrice, $Dtime]);
Try this
$sql = ("INSERT INTO stocks (Stock,Price, TimeD)
VALUES('$StockName', '$FUMUKUPrice', '$DTime')");
I managed to fix it using:
$sql = "INSERT INTO `stocks` (`Stock`,`Price`, `TimeD`) VALUES ('$StockName','$FUMUKUPrice', '".date('Y-m-d',strtotime($Dtime))."')";

PHP / MySQL. Could not update data: Query was empty

First of all I like to say that I'm super bad at this type of stuff so my code can be totally useless.
The mission is to create a system that will ask the user to scan two ID's, userID and itemID. After the scan has been successful I want these values to be transported to a PHP document.
Here I'd like to run a MySQL query which will update the value of userID where itemID match the database.
So my problem is that I get this message after running my query:
userID:202 itemID:8204 Could not update data: Query was empty. And ofc my database remains empty.
I think the problem is that the query can't read the $_GET variables. But I have no clue so please help me, Thanks!
This is my form:
<form id="checkin" name="checkin" action="test.php">
<input type="button" onclick="checkIn()" value="Check in Item">
</form>
The function:
<script>
function checkIn(){
var userID=parseInt(prompt ("Scan userid"), 10);
var itemID=parseInt(prompt ("Scan itemid"), 10);
if(userID!=null && itemID!=null){
window.location.href= "http://localhost/webapp/test.php?userID=" + userID + "&itemID=" + itemID;
alert ("working so far userID:"+ userID + " --- itemID:" + itemID);
}
}
</script>
At last the PHP:
$con = mysql_connect("localhost", "root", "", "book1");
$db = mysql_select_db('book1');
if (isset($_GET["userID"]) && isset($_GET["itemID"])) {
$userID1 = (int)$_GET["userID"];
$itemID2 = (int)$_GET["itemID"];
$test = "userID: ".$_GET["userID"]." "."itemID: ".$_GET["itemID"];
echo $test;
}
if (!$con) {
die('Could not connect: '.mysql_error());
}
$upd = mysql_query('UPDATE INTO booking SET userID ="$userID" WHERE ID ="$itemID');
$retval = mysql_query($upd, $con);
if (!$retval) {
die('Could not update data: '.mysql_error());
}
echo "Updated data successfully\n";
Invalid arguments # mysql_connect()
$con=mysql_connect("localhost", "root", "") or die ('Connection failed' . mysql_error());
$db = mysql_select_db('book1',$con);
UPDATE INTO need to change to UPDATE ....
Also you have userID assigned to variable $userID1 and itemID assigned to $itemID2. But in your query it is wrong. Query is updated now.
Mysql Manual
Also missing quotes at WHERE ID ="$itemID'
$upd = mysql_query("UPDATE booking SET userID ='$userID1' WHERE ID ='$itemID2'", $con);
P.S. Usage of mysql_* functions is not advised, instead use mysqli_*
Your DB connection string might looks mysqli_. In mysql_, you don't want to specify the DB Name as parameter.
$con=mysql_connect("localhost", "root", "", "book1");
This should be,
$con=mysql_connect("localhost", "root", "");
You add unnecessary INTO in UPDATE query..
Refer the manual
Try this,
UPDATE booking SET ....
instead of,
UPDATE INTO booking SET ....
You might also want to read this: Why shouldn't I use mysql_* functions in PHP?
Correct your connection as per manual and also correct Update syntax
Check PHP CONNECTION Manual
$con=mysql_connect("localhost", "root", "") OR die('Could not connect');
$db = mysql_select_db('book1',$con);
if(isset($_GET["userID"]) && isset($_GET["itemID"])){
$userID1= (int) $_GET["userID"];
$itemID2= (int) $_GET["itemID"];
$test = "userID: ". $_GET["userID"] . " " . "itemID: ". $_GET["itemID"];
echo $test;
}
$upd = mysql_query("UPDATE booking SET userID='".$userID."' WHERE ID=$itemID");
$retval = mysql_query( $upd);
if(! $retval){
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
}
#user3751216 the error of the "syntax" problem it's generated on this line
$upd = mysql_query("UPDATE booking SET userID='".$userID."' WHERE ID=$itemID");
$retval = mysql_query( $upd);
If you put your code like this, it should resolve the problem of the SQL syntax
$upd = ("UPDATE booking SET userID='".$userID."' WHERE ID=$itemID");
$retval = mysql_query( $upd);
Let me now if you already resolve the problem.

How to insert a php variable in an sql query? Mistake in my query?

I wrote this simple code to delete a blog from the sql table. But its giving an error
Could not delete data: Unknown column '$qid' in 'where clause'
Cant understand why. $qid is the variable while just qid is the column name and its giving me this error.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('trial1');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
function check_login(){
return 12;
}
$return_array = array();
if( check_login()!=NULL){
$qid =1;
$sql='DELETE FROM blog_post WHERE qid = $qid';
$retval = mysql_query($sql, $conn);
if (!$retval){
die('Could not delete data: ' . mysql_error());
$return_array["success"] = 0; //If deletion unsuccessful
echo json_encode($return_array);
}
else{
$return_array["success"]=1; //If deletion successful
echo json_encode($return_array);
}
}
?>
Variables will not be parsed under single quotes. Enclose the SQL query under double quotes ".
$sql="DELETE FROM `blog_post` WHERE `qid` = $qid"; //<-- Like this.
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, Prepared Statements of MySQLi or PDO_MySQL extension should be used to ward off SQL Injection attacks !
You should wrap your input in the sql with single quotes :
$sql="DELETE FROM `blog_post` WHERE `qid` = '$qid'";
Very first you need to make sure you have a column name qid in table.
Then try:
$sql='DELETE FROM blog_post WHERE qid ='.$qid;

Cannot update database using variable names?

I just can't get this query to work when updating records in a mySQL database:
In my update script I POST the contents of two variables, and I can see the contents when I print them:
$orderno =$_POST['order_no'][$i];
$status =$_POST['order_status'][$i];
My SQL query looks like:
<?php
if(isset($_POST['order_status']))
{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$orderno =$_POST['order_no'][$i];
$status =$_POST['order_status'][$i];
print_r($_POST['order_no']);
$sql = 'UPDATE Orders SET status="' . '$status'. '" WHERE Orderno="' .'$orderno' . '"';
echo $sql;
mysql_select_db('PurchaseOrders');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
?>
This is inserting the variable name itself into the database and not the value of the variable which is printed? Many thanks
Try the following:
$sql = 'UPDATE Orders SET status="' . $status. '" WHERE Orderno="' .$orderno . '"';
As well take into consideration security. You are not validating string (order number or status) in any shape or form.
As well mysql functions are deprecated, consider using mysqli
$sql = "UPDATE Orders SET status='" . $status . "' WHERE Orderno= '" . $orderno . "' ";
When you encapsulate a variable in single quotes, PHP will take it "as is". It won't evaluate any variables found inside the quotes.
Have a look at the difference between single quotes and double quotes.
use the query like this
$sql = "UPDATE Orders SET status='$status' WHERE Orderno='$orderno'";
you are using variable inside single quotes. Inside single quotes variable name is not resolving, you have to use double quotes for this. In double quotes variable value is coming.

Categories