Cannot update database using variable names? - php

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.

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

SQL Query 'WHERE EXISTS' if a column returns empty

I am using this sql query as part of a PHP script to take user input (being applied to variables $condition1-$condition4) and compare it against a MySQL database and return relevant results.
My problem is that not all the forms on the site output a $condition4 value so it is not always inputted into the script/query.
I tried using the EXISTS predicate within the SQL query but could not get it to work.
Here is the query as i have it working:
$sql = "SELECT columnXYZ
FROM table_1
WHERE condition1 = '" .$condition1."'
and condition2 = '" .$condition2."'
and condition3 = '" .$condition3."'
and condition4 = '".$condition4."'";
Do I need to determine whether $condition4 was inputted before i run the query or is there a way to use the WHERE EXISTS predicate to achieve this?
The whole script: (var_dump to see the results of the query)
<?php
$condition1 = $_POST['condition1'];
$condition2 = $_POST['condition2'];
$condition3 = $_POST['condition3'];
$condition4 = $_POST['condition4'];
$dbhost = 'localhost';
$dbuser = 'admin';
$dbpass = 'pwd';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT columnXYZ
FROM table_1
WHERE condition1 = '" .$condition1."'
and condition2 = '" .$condition2."'
and condition3 = '" .$condition3."'
and condition4 = '".$condition4."'";
mysql_select_db('database_1');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$columnXYZ = $row['columnXYZ'];
var_dump($columnXYZ);
}
mysql_close($conn);
?>
The query works fine when $condition4 is inputted, as a work around for forms that do not have a $condition4 i have just been directing to a similar php script that has the $condition4 removed.
To clarify my question: Can i use the EXISTS predicate in a SQL query to determine if an input has a value or do i need to do so with PHP or some other method beforehand?
Just check if $condition4 is empty() before adding that part to your SQL query.
$sql = "SELECT columnXYZ
FROM table_1
WHERE condition1 = '" .$condition1."'
and condition2 = '" .$condition2."'
and condition3 = '" .$condition3."'";
if !(empty($condition4)){
$sql .= "' and condition4 = '".$condition4."'";
}
As Seth mentions, google for 'SQL injection' if you're going to put this anywhere near the public internet.
When using empty() to check, the value of $condition4 might be null since empty allows for NULL values. I'm still learning PHP; however, would isset() be a better approach? Otherwise there might be condition4 = null
Also as that person commented on your post, please remember to validate all user input before you place it in a sql query or other places.
http://php.net/manual/en/function.isset.php

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;

Trying to update an entry in a database

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

Categories