I am still new to PDO and am having trouble getting the update statement below to work. I want to be able to update the name field by just appending to the current value with a comma and the new name. Resulting name field should be like james,doug,paul,etc. This is probably a simple answer but I haven't been able to find a solution through a lot of googling!
Thanks in advance
$stmt = $db->prepare('UPDATE table SET name = concat(name, ',' :name) WHERE id = :id');
$stmt->execute( array('name' => $name, 'id' => $id) );
you lack comma inside your concat.
$stmt = $db->prepare("UPDATE table SET name = concat(name, ',', :name) WHERE id = :id");
^ ^ here ^
Related
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;
I'd like to create a 'one fits them all' function for updating an SQL database.
Imagine I have a database table with columns :
id (int)
col1 (varchar)
col2 (varchar)
col3 (varchar)
col4 (varchar)
col5 (int)
Now the php script receives some JSON like this :
{ id : 5,
col3 : "somevalue",
col5 : 17 }
So I would like to recreate an update function with a clean prepared MySqli statement:
$stmt = $db->prepare("UPDATE `table` SET `col3` = ?, `col5` = ? WHERE `id` = ?;");
$stmt->bind_param("sii", $obj->col3, $obj->col5, $obj->id);
$stmt->execute();
Seems quite simple at first, but I don't get how I'm supposed to dynamically recreate the argument list inside the bind_param method. It does not take an array, but all values in different parameters..
Question : How to recreate the bind_param without knowing on the forehand how many columns and what kind they are.
listing the kind of variable is simple, iterating over all object parameters and creating a string containing "sii" in this case..
json object properties always reflect table's columns.
As suggested by Rajdeep Paul, I switched to PDO.
PDO offers more flexibility, in a way it accepts an array of named parameters. Final code looks like this for anyone who wants to achieve the same :
$data = $_POST['carData'];
$params = [];
$updateString = "";
foreach ($data as $key => $value)
{
if($key != "id")$updateString .= $key." = :".$key.",";
$params[':'.$key] = $value;
}
$updateString = rtrim($updateString, ","); //remove last ,
$stmt = $pdo->prepare("UPDATE cars SET ".$updateString." WHERE id = :id");
$stmt->execute($params);
I just remove the 'id' of the update string as it really makes no sense, the update is on 1 id in particular, but could probably be ignored.
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();
Ive just started learning PDO and I'm struggling by simply inserting a new record based from
$lastid = $db->lastInsertId();
The ID gets created in the database table from another function.
But nothing happens when i try to insert a new record based on that ID.
function add_name($last_id, $name) {
$db = some_db();
$query = "INSERT INTO team (name) VALUES (:name) WHERE id = '".$last_id."'";
$stmt = $db->prepare($query);
$stmt ->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();
}
INSERT ... WHERE is not valid SQL. If you are inserting a new record, an autoincremnt ID will be generated at that time (if you have such defined for the table).
If you are trying to INSERT a new row into a related table with the last id from another table, then you would set that value as one of your column inputs. So the workflow would look like this:
INSERT [column data for table_a] INTO table_a
[GET autoincrement from last insert]
INSERT (table_a_foreign_key_column, [other table_b columns]) VALUES (table_a_id, [other table_b values) INTO table_b
UPDATE:
Since UPDATE is what you want, you can make update like this:
UPDATE team
SET name = :name
WHERE id = :id
You should use parameters for both name and id values. It is still not clear to me why you would need to make an insert and then an update within the same script execution. It's not like you received any more input from the user that you did not already have. I would guess you could just insert this name values when first creating the record and save yourself the extra trouble of multiple queries.
i think your sql query is wrong, try this:
function add_name($last_id, $name) {
$db = some_db();
$query = 'INSERT INTO team (id, name) VALUES (:id, :name)';
$stmt = $db->prepare($query);
$stmt ->bindParam(':name', $name, PDO::PARAM_STR);
$stmt ->bindParam(':id', $last_id, PDO::PARAM_INT);
$stmt->execute();
}
MySQL Insert Where query
...i am not getting any further.
my database contains a column 'name' = 'John Richards'
i try to query it like:
$act = "John Richards";
prepareEditing($act);
function prepareEditing($act) {
include ($_SERVER['DOCUMENT_ROOT']."/final_ritg/includes/dbconnect.php");
$act = str_replace(" ", " ", $act);
$sql = "select `name`,`genre`, `members`, `story`, `image`, `contact_fname`, `contact_lname`, `contact_phone`, `contact_email` from `festival`.`act` where `name` = :name ;";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $act);
$stmt->execute();
echo $stmt->rowCount();
}
when 'name' only contains a single word, like 'john', the function returns 1 ($act holds 'john' as well).
How do I have to prepare my query?
Edit: I am using utf8 across the board.
Edit: This is the prepare stmt I use to insert the data:
$stmt->bindParam(':name', str_replace(' ',' ',$name));
I did so, because the query result would have been cut off at the whitespace when trying to retrieve it.
As it turns out, my mistake was not in the php, but inside the html.
I was creating a select list from a table. because the names were unique, i used those as primary keys and as value for each select-option...those dont like whitespace.
The solution here would be to either add a numbered index to the table or to do some string-conversion (but that would cause a lot of extra work preparing the string for the query) I dont yet know how I would be going over this.
Anyways, maybe another beginner runs into the same trap and finds this useful.