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.
Related
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.
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))."')";
This question already has answers here:
Selecting random rows with MySQL
(3 answers)
Closed 8 years ago.
bellow you can see my table. In this table we have 300 quotes that I'm trying to fetch my at random and display it on the page but I have not succeeded. The column containing the texts has the name "fortune_text". here is my attempt code:
<?php
$username = "fortunes";
$password = "xxxx";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
// connect to database
mysql_select_db("fortunes");
// query the databse
$query = mysql_query("SELECT 'fortune_text' FROM 'fortunes' ORDER BY RAND()");
echo "$query";
?>
try using shuffle() function of php to randomize array that comes from database and then echo the first index of that variable.
Hi here is the modified version of your sample, which fetch text by rand order.
I suggest you to use limit when you print result to page if you have later many rows, checking for error if any. Important line is echo mysql_result($result);
<?php
$username = "fortunes";
$password = "xxxx";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
// connect to database
mysql_select_db("fortunes");
// query the databse
$result = mysql_query("SELECT 'fortune_text' FROM 'fortunes' ORDER BY RAND()");
if (!$result) {
die('Could not query:' . mysql_error());
}
echo mysql_result($result);
mysql_close($dbhandle);
?>
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;
This question already has answers here:
How to test if a MySQL query was successful in modifying database table data?
(5 answers)
Closed 1 year ago.
I'm going to insert about 500 records in a table using one query :
$sql = "INSERT IGNORE INTO `table_name` (`field1`,`field2`)
VALUES ('val1','val2') ('val3','val4') ... ";
// php_mysql_insert_function
How can I find out haw many rows are inserted in after executing query ?
The answer is affected_rows
$db = new mysqli('127.0.0.1','...','...','...');
$sql = "INSERT IGNORE INTO Test (id,test) VALUES (1,2),(1,3),(2,2),(3,4)";
$ins_test = $db->prepare($sql);
$ins_test->execute();
echo $db->affected_rows;
In this example Test has 2 columns id and test (both integer) and id is the primary key. The table is empty before this insert.
The programm echos 3.
Try this:
Procedural style of coding:
<?php
$host = '';
$user = '';
$password = '';
$database = '';
$link = mysqli_connect($host, $user, $password, $database);
if(!$link)
{
echo('Unable to connect to the database!');
}
ELSE {
$sql = "INSERT IGNORE INTO `table_name` (`field1`,`field2`) VALUES ('val1','val2'), ('val3','val4')";
$result = mysqli_query($link, $sql);
echo mysqli_affected_rows($link);
}
mysqli_close($link);
?>
mysqli_affeccted_rows counts the number of inserts. I think that #wikunia's answer will probably yield the same result. I was in the process of answering you question, before wikunia beat me to it. I place it anyway.