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
Related
I am not able to update MySQL table using PHP. How can I do that?
I have tried by changing the order of double quotes.
$name=mysql_real_escape_string($_POST["steel"]);
$db->execute("UPDATE order SET need=$name WHERE raw-id='1'");
It should store $name in the database.
You should wrap your $name with single quote, because you are trying to pass a string into the SQL
$db->execute("UPDATE order SET need='$name' WHERE `raw-id`='1'");
You should wrap your {$name} with single quote and bracket to , because need row is a string into the SQL
$db->execute("UPDATE order SET need='{$name}' WHERE `raw-id`='1'");
You need to wrap your column name in back-ticks because it has a dash in it, e.g:
$db->execute("UPDATE order SET need = '$name' WHERE `raw-id` = 1");
By referring to the manual I think you should first prepare your
query and then use execute() method. Something like this:
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = $mysqli->prepare($query);
$stmt->execute();
Alright so I have two tables that I am working with.
The first is set up something like these tables
Destination
IDDestination Name IDCity IDState
1 Scottsdale 3 4
2 Miami 5 7
and
Destinations_Citites
IDDestinationCity IDDestination IDCity
1 1 3
2 2 5
Now with my plugin I have an add a new destination button which adds a new destination with its Name, IDCity and IDState filled out by the user and the IDDestination is automatically generated.
So what I want to figure out how to do is to grab that automatically generated IDDestination # and enter it into the Destinations_Cities table with out having the user do anything else.
Basically how can I insert the automatically generated IDDEstination that was just created and throw it into my other table without the user having to add it themselves.
Here is the code I am using to Insert and Update for my add destinations button
if(isset($_POST['Add_Destination'])) {
$idstate = $_POST['idstate1'];
$idcity = $_POST['idcity'];
$name = $_POST['addname'];
$SQL="INSERT INTO destination (name, IDCity, IDState) VALUES ('". $name ."','". $idcity ."','". $idstate ."')";
$SQL1="UPDATE city SET is_active='1' WHERE IDCity='$idcity'";
$result=mysql_query($SQL) or die (mysql_error());
$result1=mysql_query($SQL1) or die (mysql_error());
print $SQL;
print $SQL1;
}
You can get the most recent auto-increment id generated during your session:
$dest_id = mysql_insert_id();
Refer to the documentation: http://php.net/manual/en/function.mysql-insert-id.php
Not exactly about your question, but I echo the comment above that you should protect your queries from SQL injection vulnerabilities. Don't copy PHP variables into SQL strings unless you have made sure the variables are made safe.
If a variable is supposed to be an integer, use (int) to cast it to an integer as you read it.
For string values, use escaping provided by the MySQL API.
Also, there's no need to do all the . concatenation if you're just putting simple variables inside PHP strings. There's no need in SQL to put quotes around integer literals.
Here's an example:
if(isset($_POST['Add_Destination'])) {
$idstate = (int) $_POST['idstate1'];
$idcity = (int) $_POST['idcity'];
$name = mysql_real_escape_string($_POST['addname']);
$SQL="INSERT INTO destination (name, IDCity, IDState)
VALUES ('$name', $idcity, $idstate)";
$dest_id = mysql_insert_id();
$SQL1="UPDATE city SET is_active='1' WHERE IDCity='$idcity'";
. . .
If you convert your code to use PDO, you can use SQL query parameters, in which case you wouldn't need to worry about escaping and such.
This query had previously worked, now when it is run again we get Unknown Column in field list error.
The query works well if we do not use variables and set raw data. The columns match those in the database.
$update_order_id = "UPDATE order_tbl SET o_process=$process, o_payment=$payment, o_paymentType=$paymenttype WHERE o_id=$orderid AND o_active='1'";
You need wrap single quotes for the values in the query as
o_process='$process'
etc
So the query will be as below. For string values its necessary.
$update_order_id = "UPDATE order_tbl
SET o_process='$process',
o_payment='$payment',
o_paymentType='$paymenttype'
WHERE o_id= '$orderid' AND o_active='1'";
You might need to surround your variables with quotes, only integer columns doesn't need quotes.
$update_order_id = "UPDATE order_tbl SET o_process='$process', o_payment='$payment', o_paymentType='$paymenttype' WHERE o_id='$orderid' AND o_active='1'";
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'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.