I'm using this query (I changed it):
// SQL query
$squl = "INSERT INTO 'messages' ('id','name' ,'email' ,'subject' ,'content','userid') VALUES ( null,'".$name."', '".$mail."', '".$subject."', '".$content."','');";
// mysql query
$query = mysql_query($squl) or die("message query problem: ". mysql_error());
I get this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''messages' ('id','name' ,'email' ,'subject' ,'content','userid' )VALUES ( null,'' at line 1
What is causing this?
.``) You used a period here instead of a comma so the function is only receiving 5 columns when it needs 6.
Update:
As the commenter below points out, you've replaced the backticks with quotation marks.
$squl="INSERT INTO `messages` (`id`,`name` ,`email` ,`subject` ,`content`,`userid` )VALUES ( null,'$name', '$mail', '$subject', '$content','');";
(id,name ,email ,subject ,content,userid )
( NULL,".$name.", ".$mail.", ".$subject.", ".$content."**.**``);
you are using '.' instead of ,
Well, that's about the clearest message you get from SQL. You try to insert 5 values into 6 columns.
The problem that there's no comma between the last two values. Instead there's a . which makes the parser think it's only one value.
You are trying to insert into 6 columns:
id
name
email
subject
content
userid
But have only specified 5 values:
NULL
$name
$mail
$subject
$content
You've got a dot where you should have a comma:
".$subject."`, `".$content."`.``);";
Change that last dot to a comma and you should be golden
You've got 6 fields in your fields list, but are inserting only 5 values in your values list. Looks like you've got a . instead of a ,:
`, `".$subject."`, `".$content."`.``
^--- here
As well, there is NO reason to use repeated string concatenation as you are. PHP can insert variables into double-quoted strings quiet easily:
$sql = "INSERT INTO .... (...) VALUES (NULL, '$name', '$mail', '$subject', '$content', '')";
Note that the 'null' value is not quoted. Backticks are there to escape reserved words. If you intend to insert a real database null, then use the bare word null. If you want a literal string 'null' to go in, then quote it normally: 'null'.
You have six fields listed the first set of parentheses and only five fields in VALUES. That's what column count means.
Related
I have the following MySQL query which needs to be passed to query(). I'm having trouble understanding it.
INSERT INTO admin (student_name, student_email, student_city) VALUES ('mark','mark#mark.com','newark');
The place I got the script from has given the following,
$sql = "INSERT INTO students (student_name, student_email, student_city) VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";
The part I'm having trouble understanding is ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')
What is happening there? All those inverted commas and periods have got me confused.
Here the SQL is being concatenated using the . in PHP.
So, lets take a look at this this:
// 12 3 45678
// vv v vvvvv
('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";
After the bracket, the single quote ' is to open the MySQL single quote.
And then the double quote " ends the string in PHP.
Then, you use PHP . to join the current PHP string with $_POST['stu_name']
And then join it to another PHP string using .
Open a PHP string using double quotes ".
And finally once it's open you need to close the MySQL string you opened using '.
Comma, to enter the second value
A single quote' to open a string in MySQL. Then the process repeats itself.
This is to long for a comment:
('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";
The whole query need to be warped in double quotes , but when you want to concatenate a variable ->
('".$_POST["stu_name"] <-- this part is leaving the query as
('Value
('".$_POST["stu_name"]."', <-- this part is leaving the query as
('Value',
Each value inside the comma needs to be concatenate into two single quotes on both their sides, hence the single quotes signs. Each dot (.) is concatenating the variable into the existing string and back into the string.
Try this, you had issue of quotes only :
["stu_name"] chnaged this to ['stu_name']
$sql = "INSERT INTO students (student_name, student_email, student_city) VALUES ('".$_POST['stu_name']"','".$_POST['stu_email']."','".$_POST['stu_city']."')";
if using POST method
$stu_name = $_POST["stu_name"] //mark
$stu_email = $_POST["stu_email"] //mark#mark.com
$stu_city = $_POST["stu_city"] //newark
$sql = "INSERT INTO students (student_name, student_email, student_city) VALUES ('$stu_name','$stu_email','$stu_city')";
The above is same as
$sql = "INSERT INTO admin (student_name, student_email, student_city) VALUES ('mark','mark#mark.com','newark')";
Simply put a line after the query like this
echo "INSERT INTO students (student_name, student_email, student_city) VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";
It will print the SQL query with values. Note the ' in the values. Here you are passing string values in to table, so you use ' and commas to separate the values. Hope this helps you in understanding quickly.
Note: Do not use it on production server. Use it on your local server.
when you insert a string into Database my sql query, you MUST plus " or ' character
By your issue, the query clause is:
$sql = "INSERT INTO students (student_name, student_email, student_city) VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')";
The $_POST["stu_name"], $_POST["stu_email"], $_POST["stu_city"] are the variables that you received by form with $_POST method
Best regards,
Tuyen
I wrote this mySQL query and I keep getting an error. Included are the query and the error:
mysql_query("INSERT INTO wp_usermeta(umeta_id, user_id, meta_key, meta_value)
VALUES(NULL, $value, $lastkey, $time())") or die(mysql_error());
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
Any help would be greatly appreciated! Thank you.
If your column in 'umeta_id' is default NULL then you don't need to specify it on the insert. 'CURTIME()' is an SQL function that returns current time. Should work if the column 'meta_value' is set to hold only time. I'm assuming you are using PHP. I've found including the variables in tick marks ' works. Also mysql_query is deprecated. You should use mysqli_query(yourDatabaseConnection, yourQuery)
mysql_query("INSERT INTO wp_usermeta (user_id, meta_key, meta_value)
VALUES ('$value', '$lastkey', CURTIME())") or die(mysql_error());
You are passing String thru query to mysql Without putting in Single/Double quotes. Use
mysql_query("INSERT INTO wp_usermeta(umeta_id, user_id, meta_key, meta_value)
VALUES(NULL, $value, '".$lastkey."', '".$time()."')") or die(mysql_error());
this query with string concatenation.
Check type of values was matched with database and umeta_id allow be null .
may be on of field has autoincrement or not null check database again .
you should use NOW()
mysql_query("INSERT INTO wp_usermeta(umeta_id, user_id, meta_key, meta_value)
VALUES(NULL, $value, $lastkey, NOW())") or die(mysql_error());
Everyone!
I am working on application using php and mysql. Basically, initially, I am inserting the new data entries using html form into the database where store# is my primary key. For now I can not update the existing store# (as its my primary key) and get a message saying "Duplicate entry for store 967 (example)".
I want to update the "store" table if entery exists. Here is my code posted below, but I am getting another error message
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '['967'],address=['500 kipling avenue 1'],dsm_name=['n/a'],phone=['416-967-' at line 1
I am not sure if I am using the if conditional at right spot.
**$sql = "INSERT INTO `stores`(`store_num`, `address`, `dsm_name`, `phone`, `router_type`, `high_speed_pri`, `dsl_log`, `dsl_pass`, `secondary_conn`, `sec_dsl`, `sec_pass`) VALUES ('$store' , '$address', '$dsm', '$phone', '$router', '$highspeedpr', '$dsllog', '$dslpas', '$secondary_conn' , '$secdsl' , '$sec_pass')";
$mysqli_query = "SELECT * from 'stores' WHERE $store = 'store_num'";
if ($mysqli_query == TRUE){
$sql = "UPDATE `stores` SET `store_num`=['$store'],`address`=['$address'],`dsm_name`=['$dsm'],`phone`=['$phone'],`router_type`=['$router'],`high_speed_pri`=['$highspeedpr'],`dsl_log`=['$dsllog'],`dsl_pass`=['$dslpas'],`secondary_conn`=['$secondary_conn'],`sec_dsl`=['$secdsl'],`sec_pass`=['$sec_pass'] WHERE 1";
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>**
Replace instead of Insert
Since your update statement includes all the same fields as Insert, you can simply use a REPLACE Statement. As stated on the linked documentation:
REPLACE works exactly like INSERT, except that if an old row in the
table has the same value as a new row for a PRIMARY KEY or a UNIQUE
index, the old row is deleted before the new row is inserted. See
Section 13.2.5, “INSERT Syntax”.
So, changing the code to the following should work:
$sql = "REPLACE INTO `stores`(`store_num`, `address`, `dsm_name`, `phone`, `router_type`, `high_speed_pri`, `dsl_log`, `dsl_pass`, `secondary_conn`, `sec_dsl`, `sec_pass`) VALUES ('$store' , '$address', '$dsm', '$phone', '$router', '$highspeedpr', '$dsllog', '$dslpas', '$secondary_conn' , '$secdsl' , '$sec_pass')";
Error Reason
Your problem is with the syntax in the update statement. What is store_num, is it a number or a string?
You should change your syntax to not include the square brackets in the actual mysql query.
If $Store is Number:
=['$store'], to =$store
If $Store is Text:
=['$store'], to ='$store'
Final Recommendation
Even better though will be use prepared statements which are also secure and avoid against SQL injection attacks.
You can do this logic with a single query, using on duplicate key update. First, you have to define store_num as a unique key, if it is not already a unique or primary key:
CREATE UNIQUE INDEX idx_stored_storenum on stores(store_num);
Then use this insert:
INSERT INTO `stores`(`store_num`, `address`, `dsm_name`, `phone`, `router_type`, `high_speed_pri`,
`dsl_log`, `dsl_pass`, `secondary_conn`, `sec_dsl`, `sec_pass`
)
VALUES ('$store' , '$address', '$dsm', '$phone', '$router', '$highspeedpr',
'$dsllog', '$dslpas', '$secondary_conn' , '$secdsl' , '$sec_pass')
ON DUPLICATE KEY UPDATE address = values (address),
dsm_name = values(dsm_name),
. . .
sec_pass = values(sec_pass);
Your particular problem is the square braces, which MySQL doesn't recognize.
I'm making a search engine based on the API of Faroo.com (http://www.faroo.com/hp/api/api.html) for a school project. I would like to index the index of Faroo, so that users (in my situation, children) can vote up or vote down individual results.
What my (PHP)-script is like:
Look in the MySQL-database if the query exists.
yes => load the results from the database and show them to the user
no => load the results from Faroo, show those results to the user and store them in the database
My database looks like this:
I'm getting all the data stored in the columns from the Faroo API, except for the 'id'-column.
The last part (of storing the Faroo-data in the database) is where it goes wrong:
for($x=0; $x<$tel; $x++){
$sql = "INSERT INTO queries (`id`, `query`, `title`, `url`, `domain`, `kwic`, `votes`) VALUES (NULL, $q, $titles[$x], $urls[$x], $domains[$x], $kwics[$x], 0);";
echo '<br />'.$x.'e query: #'.$sql.'#';
if(!$resultaat = $db->query($sql)){
die('De query kon niet worden uitgevoerd: [' . $db->error . ']');
}
$resultaat = mysqli_fetch_array($resultaat);
}
$tel is a variable which counts the number of results I get from Faroo. It gets defined before this piece of code.
When I run this code, I am getting a nice MySQL-error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'States Bureau of Mines - Wikipedia, the free encyclopedia,
www.wikipedia.org' at line 1
I've searched, and searched, but I couldn't find what the SQL-error is. I think it has something to do with the strange characters in the strings, or maybe my quotation is false?
Kind regards,
Max
I think you need to use single quotes ' for varchar columns, so change as follow
$sql = "INSERT INTO queries (`id`, `query`, `title`, `url`, `domain`, `kwic`, `votes`) VALUES (NULL, '$q', '$titles[$x]', '$urls[$x]', '$domains[$x]', '$kwics[$x]', 0)";
You also have an extra double quote at the end of the query which i removed, you won't need singles quotes for columns id and votes since they are integer fields
I am trying set variable to NULL:
$q = NULL.",";
$q .= 'abc';
and save in to database:
mysql_query("INSERT INTO table (col_a, col_b) VALUES (".$q.")")
But this generates error message:
INSERT INTO table (col_a, col_b) VALUES (,'abc')You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ','abc')' at line 2
How to save NULL into database from variable?
you can get rid of the column where you want its value to be null, eg
$q = 'abc';
mysql_query("INSERT INTO table (col_b) VALUES ($q)")
or if value is dynamic, the only problem with your current code is that you haven't include NULL in your string,
$q = "NULL,";
$q .= "'abc'";
mysql_query("INSERT INTO table (col_a, col_b) VALUES ($q)")
the your code is vulnerable with SQL Injection, please read the article below to learn how to prevent from it.
How can I prevent SQL injection in PHP?
You're concatenating NULL and trying to parse it, which in the statement, would actually read:
, abc
Instead of the expected
NULL, abc
So just write a literal "NULL" in your statement.
Pass the literal, unquoted string inside the query:
$q = "NULL,";
$q = "NULL,";
$q .= '"abc"';
Gives you NULL,"abc" which you can include in your query.
The error you posted couldn't have come from the code in the question.. where did the quotes around abc come from? You need to enclose it in quotes inside the quotes for the php variable for them to show up in the SQL too.