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))."')";
Related
This question already has answers here:
MySQL Insert query doesn't work with WHERE clause
(31 answers)
Closed 3 years ago.
I am updating the data in database from php and Getting Up Error:Query was empty with query. I badly need help. Thanks in Advance
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$myDBname = 'jsv';
$conn = mysql_connect("localhost", "root");
mysql_select_db('jsv');
if(isset($_POST['update']))
{
$nam = $_POST['namnid'];
$mandag = $_POST['mandagid'];
$tisdag = $_POST['tisdagid'];
$torsdag = $_POST['torsdagid'];
$fredag = $_POST['fredagid'];
$sql = mysql_query("INSERT INTO jsv(CA_ID,Name,Address,Amount) VALUES ('$mandag', '$tisdag', '$torsdag', '$fredag') WHERE Setup_Box_No = '$nam'", $conn);
if(!$sql )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
}
mysql_close($conn);
?>
MySQL does not support a WHERE clause in an INSERT statement. This causes your query to fail & makes $sql false.
You will need to rewrite your INSERT statement.
This answer should give you more explanation on alternative queries.
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.
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;
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
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I am trying to insert data into a database through php.. Easy enough (I thought). I can't figure out what I am doing wrong. Here is my code:
$DB_HostName = "localhost:8888";
$DB_Name = "Sample";
$DB_User = "root";
$DB_Pass = "root";
$DB_Table = "Check";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$sql = "INSERT INTO $DB_Table (name) VALUES ('Sally') ";
mysql_query($sql) or die ("Error with Result");
mysql_close($con);
It gives me an error saying "Error with Result". This means that it must be connecting to the database correctly and everything is working right except for the end part.. What am I missing? If I say (msql_error()) it also does tell me to check the $sql. I can't figure out though what I am typing in wrong.
escape your database name with backtick
$sql = "INSERT INTO `$DB_Table` (name) VALUES ('Sally') ";
or
$sql = "INSERT INTO `" . $DB_Table . "` (name) VALUES ('Sally') ";
CHECK is a MySQL Reserved Keyword.
MySQL Reserved Keyword List
How can I prevent SQL injection in PHP?
I can't stress this enough, don't use mysql_ functions, that time has gone. Use either mysqli or PDO.
A simple way to check what is wrong with your SQL query is to add an error flag on the end of your die statement mysql_query($sql) or die ("Error with Result<br>".mysql_error());
It appears in your case that check is a constraint used to limit the value range that can be placed in a column. You would need to identify that it is a table using "`":
$sql = "INSERT INTO `$DB_Table` (name) VALUES ('Sally') ";