Update a single row in SQL - php

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();

Related

Syntax issue writing conditional mySQL query in PHP

I have the following mySQL query written in the format of a PHP PDO script. I made sure to verify that all of the columns I refer to in the query exist.
So the issue seems to do with the syntax of the query itself. When executing the query in POSTMAN I see the issue seems to be where the if statement beings.
The following is the query:
$stmt = $conn->prepare('IF EXISTS (SELECT * `Table1` WHERE `code`= :code )
UPDATE `Table1`
SET `code_stat` = 2
WHERE code = :code
ELSE
INSERT INTO `Table1` (`code`,`code_stat`)
VALUES (:code, 2 ) ' );
$stmt->execute([
'code' => $_POST['code']
]);
Alternative query:
$stmt = $conn->prepare("REPLACE INTO `Table` (`code`,`code_stat`) VALUES (:code,2)");
$stmt->execute(['code' => $_POST['code']);
If the row does not exists, it will be inserted otherwise it will be updated.
https://dev.mysql.com/doc/refman/5.7/en/replace.html
Think you're just missing the ‘FROM’.
SELECT * `Table1` WHERE
should be
SELECT * FROM `Table1` WHERE

PDO update query to append data into MYSQL db using named placeholder

I'm building sql UPDATE query to append string value using only NAMED PLACEHOLDERS to the already existing value in db. please suggest necessary changes in below code to work or suggest how to use named placedholders in concat update syntax
$name="Lastname";
$stmt = $conn->prepare("UPDATE users SET name= name + :name WHERE id=:id");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':id', $id);
$stmt->execute();
Expected Output:
Before: Table has 'name' column-value "Firstname"
After code execution: 'name' column-value "FirstnameLastname"
+ is not the normal way to concatenate strings in SQL. The standard operator is || and the function concat() is usually available:
UPDATE users
SET name = CONCAT(name, :name)
WHERE id = :id;

PDO Postgres - Check if Column Exist and do action based off condition

I'm trying to check to see if a column exists.. If it does, then I want to update the value, and if it doesn't, I want to alter the table and add the column with the a value. I'm pretty new to PDO, but I'm pretty sure my query is fine, I just don't know how to handle the output from the execute() command I guess. Thanks for the help in advance!
$sth = $pdo->prepare(' SELECT ? FROM `?` WHERE column_name=? ');
$sth->bindParam(1, $column, PDO::PARAM_STR);
$sth->bindParam(2, $livetable, PDO::PARAM_STR);
$sth->bindParam(3, $column, PDO::PARAM_STR);
$sth->execute();
if ($sth) {
//Row Exist - Update Value
echo 'Row Exist';
}else{
//Row Doesn't Exist - Create column & update with value
echo 'row does not';
}
You cannot pass a table name as a bind parameter like this, you would need to use dynamic SQL to achieve this. But if you just want to check if a column exist in a table, don’t query the table directly (what if it contains millions of records ?) ; instead, query Postgres information schema, as follows :
SELECT column_name
FROM information_schema.columns
WHERE
table_name = ?
AND column_name = ?;

Insert Into with Select(PDO) and php

Ok so I need to insert some values into a table but i need to search for one of the data in the database so i tried to do it like this
$bookid = $_GET['var'];
$username = $_GET['username'];
$quer2 = "Insert Into reserved (username,bookid) VALUES ((SELECT userid FROM users WHERE username=:username),:var)";
$query2 = $dbc->prepare($quer2);
$query2 ->bindParam(':username',$username);
$query2 ->bindParam(':var',$bookid);
$query2 ->execute();
The problem is that I get this error
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "username" violates not-null constraint DETAIL: Failing row contains (6, null, 2014-09-22 13:06:33.262).
I tried the query in the database and it works so I guess that there is some error in bindParam but I can't understand what it is... So if anyone could help me I would appreciate it, thank you
change
$query2 ->bindParam(':var',$var);
to
$query2 ->bindParam(':var',$bookid);
update your query to something like this
Insert Into reserved (username,bookid)
SELECT userid, :var FROM users WHERE username=:username
just bind the params and run the query.

PHP/MySQL Insert null values

I'm struggling with some PHP/MySQL code. I am reading from 1 table, changing some fields then writing to another table, nothing happens if inserting and one of the array values is null when I would like it to insert null in the database (null values are allowed for the field). It looks a bit like this:
$results = mysql_query("select * from mytable");
while ($row = mysql_fetch_assoc($results) {
mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', {$row['null_field']});
}
Not every row has a null value and in my query there are more fields and 2 columns which may or may not be null
This is one example where using prepared statements really saves you some trouble.
In MySQL, in order to insert a null value, you must specify it at INSERT time or leave the field out which requires additional branching:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', NULL);
However, if you want to insert a value in that field, you must now branch your code to add the single quotes:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', 'String Value');
Prepared statements automatically do that for you. They know the difference between string(0) "" and null and write your query appropriately:
$stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?, ?)");
$stmt->bind_param('ss', $field1, $field2);
$field1 = "String Value";
$field2 = null;
$stmt->execute();
It escapes your fields for you, makes sure that you don't forget to bind a parameter. There is no reason to stay with the mysql extension. Use mysqli and it's prepared statements instead. You'll save yourself a world of pain.
I think you need quotes around your {$row['null_field']}, so '{$row['null_field']}'
If you don't have the quotes, you'll occasionally end up with an insert statement that looks like this: insert into table2 (f1, f2) values ('val1',) which is a syntax error.
If that is a numeric field, you will have to do some testing above it, and if there is no value in null_field, explicitly set it to null..
For fields where NULL is acceptable, you could use var_export($var, true) to output the string, integer, or NULL literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.
For example:
mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");

Categories