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();
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 am having trouble with a really simple SQL statement: UPDATE.
I would only like to update the booking_date column in a specific row.
Here is the statement I'm using:
UPDATE `coupon-codes` SET `booking_id`=:timestamp WHERE `id` = :id
I'm using PDO named placeholders.
I always get an incorrect syntax error. What am I doing wrong?
Edit:
I tried without backticks:
UPDATE coupon-codes SET booking_id = :timestamp WHERE id = :id
Still doesn't work.
Here's the error message I'm getting:
Edit 2:
Here is the error message I'm getting when using backticks:
Edit 3:
For reference, here is an INSERT statement I used before, which works without any problems:
INSERT INTO `coupon-codes` (`code`, `date`) VALUES (:code, :date)
Edit 4:
Sorry, wrongly said some things in the comments, to clarify, see this:
I am using BACKTICKS everywhere. This is the query that doesnt work:
UPDATE `coupon-codes` SET `booking_date`=:timestamp WHERE `id` = :id
I also had a typo in the original question which had booking_id instead of booking_date field, but that doesn't matter, since I'm getting a SYNTAX ERROR.
Here is the PHP code I'm trying to run it with:
$stmt = $db->prepare("UPDATE `coupon-codes` SET `booking_date`=:timestamp WHERE `id` = :id");
$stmt->bindParam(':timestamp', $time);
$stmt->bindParam(':id', $id);
$stmt->execute();
Basic MySQL syntax:
'foo' - single-quotes. turns the quote word into a string literal
`foo` - backticks. used to escape table/fieldnames that happen to be reserved words
SELECT 'select' FROM ... -- select the literal word "select" from some table
SELECT `select` FROM ... -- select the field NAMED "select" from some table
SELECT select FROM ... -- syntax error - using a reserved word "select"
Given your error messages, you probably have one of the following:
UPDATE 'coupon-code' ... -- can't update a string. must specify a table name
UPDATE coupon-code ... -- math operation: coupon MINUS code - not a table name
Have you tried to use Predefined Constants (http://php.net/manual/en/pdo.constants.php);
Example:
$stmt = $db->prepare("UPDATE `coupon-codes` SET `booking_date`=:timestamp WHERE `id` = :id");
$stmt->bindParam(':timestamp', $time, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
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 am new to php, in my sql table I have a row with these columns:
id, custid, name, value
id is auto increment, custid is unique value, name is a enable (status parameter) and value set to true or false.
Now I just want to select a case where
$sql = 'cu_id FROM table WHERE name = 'enable' AND value = 'true'' ;
in a PHP file, but my php file says, line has syntax error, at enable.
Can anyone please have a look what is it :)
use double quotes,
$sql = "cu_id FROM table WHERE name = 'enable' AND value = 'true'";
but the best way to do is to use prepared statement to avoid from sql injection.
You have following errors in your query:
You are using single quotes within single quotes. You can fix this by wrapping double quoting the query string and keeping single quotes for column values. Or you can choose to escape the single quotes used in the values with a backslash, e.g. \'enable\'
Your table name is one of MySQL reserved words i.e. table. When you use one of MySQL reserved words you need to quote them with backticks e.g `table`.
Please try the following:
$sql = "cu_id FROM `table` WHERE name = 'enable' AND value = 'true'";
Use double quotes and instead of using true and false you can use 1 and 0. With default value 0 or 1 as you wish so that query will look like. You can also replace value as status
$sql = "select cu_id FROM table WHERE name = 'enable' AND status = 0";
Pass your query with in the double coats, it is the best practice
$sql = "cu_id FROM table WHERE name = 'enable' AND value = 'true'" ;
i want that if a record doesnt exist i add it otherwise update it... but it doesnt work, whats the wrong with this code:
<?php
$user_id=$_POST['user_id'];
$user_email="user_email";
$last_stage=$_POST['last_stage'];
$score=$_POST['score'];
$note=$_POST['note'];
$con=mysqli_connect("localhost","ferfer","Drfrj","ferfw");
$result = mysqli_query($con,"SELECT user_email FROM rating WHERE user_email='".$user_email."'");
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
//echo "exist";
mysqli_query($con,"UPDATE rating SET user_id=".$user_id.", user_email='".$user_email."', last_stage=".$last_stage.", score=".$score.", note='".$note."' WHERE user_email='".$user_email."'";
mysqli_close($con);
}else{
//echo "does not exist";
mysqli_query($con,"INSERT INTO rating(user_id, user_email, last_stage, score, note)VALUES (".$user_id.",'".$user_email."',".$last_stage.",".$score.",'".$note."') ");
mysqli_close($con);
}
?>
You can actually do it in a single query since MySQL has implemented INSERT ... ON DUPLICATE KEY UPDATE which basically INSERTs a record if it does not exists otherwise UPDATEs it.
The first thing you need to do is to add a UNIQUE column on the table. In your example I see that user_email is the column you are searching for existence. If this is not unique, you need to alter the table for UNIQUE constraint
ALTER TABLE rating ADD CONSTRAINT tb_uq UNIQUE(user_email)
after it has been implement, build a query like this,
INSERT INTO rating(user_id, user_email, last_stage, score, note)
VALUES($user_id, '$user_email', last_stage, score, '$note')
ON DUPLICATE KEY UPDATE
user_id = $user_id,
last_stage = $last_stage,
score = $score,
note= '$note'
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
$user_email="user_email";
should be changed to
$user_email=$_POST['user_email'];
And missing ( simbol, as #Yogesh Suthar said. You should also consider escaping characters in strings, using i.e. mysql_real_escape_string function.
you forgot ) here
mysqli_query($con,"UPDATE rating SET user_id=".$user_id.", user_email='".$user_email."', last_stage=".$last_stage.", score=".$score.", note='".$note."'
WHERE user_email='".$user_email."'");
^ // here
Better way is to use
REPLACE INTO `rating` (user_id,user_email,last_stage,score,note)
VALUES(#user_id,#user_email,#last_stage,#score,#note) WHERE user_email=#email
use also binding and prepared statements to make it more secure. Your code is very insecure because you have nor escape functions neither casting.
Example of using binding with PHP. $dbh is PDO object.
$stmt = $dbh->prepare("REPLACE INTO `rating` (user_id,user_email,last_stage,score,note)
VALUES(#user_id,#user_email,#last_stage,#score,#note) WHERE user_email=#email");
$stmt->bindParam('#name', (int)$user_id);
$stmt->bindParam('#user_email', $user_email);
$stmt->bindParam('#last_stage', $last_stage);
$stmt->bindParam('#score', $score);
$stmt->bindParam('#note', $note);
more on http://pl1.php.net/pdo
with binding you don't have to escape strings because it goes straight into the database layer without it having to be crudely spliced into the SQL statement.
The MySQL REPLACE statement works like the INSERT statement with the additional rules:
If the record which you want to insert does not exist, the MySQL REPLACE inserts a new record.
If the record which you want to insert already exists, MySQL REPLACE deletes the old record first and then insert a new record.
$user_email="user_email"; should be $user_email=$_POST["user_email"];