Insert Into with Select(PDO) and php - 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.

Related

Update a single row in SQL

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

Last insert id issue--How to fetch it

I'm using $id = mysqli_insert_id($connection); to get the last inserted id, but in case if it updates any record in the table, it returns 0 as last inserted id.
Is there any way to handle this?
I want to get id each time weather it's inserting or updating.
Thanks
Edit
I need this id to be used for inserting data into table2
id from tab1
put data into tab2 where id from tab1 is FK
and most important, I'm not using the update with where clause
Here is my code that I'm using
$val = utf8_encode($val);
mysqli_set_charset($connection, 'utf8');
mysqli_query($connection, "SET NAMES 'utf8'");
mysqli_query($connection, "SET FOREIGN_KEY_CHECKS = 0;");
$sql = "INSERT INTO leaks($insert) VALUES($val)";
$sql .= " ON DUPLICATE KEY UPDATE `url` = '".mysqli_real_escape_string($connection,$data['url'])."';";
mysqli_query($connection, ($sql))or die(mysqli_error($connection)."<br />".print($sql));
$id = mysqli_insert_id($connection);
$proofs['leaks_id'] = $id;
mysqli_query($connection, "SET FOREIGN_KEY_CHECKS = 0;");
print_r($id);
$this->insertProofs($connection, $proofs);
connection::close_connection($connection);
Please note down that $this->insertProofs($connection, $proofs); inserts data to table2 on the base of key passed to it
On INSERT
After executing an INSERT query, using mysqli_insert_id() is absolutely fine.
On UPDATE
Depending on your update, you;
Would know the id's you're updating
Know the criteria to search for the id's from the update.
For example, if your UPDATE was something like;
UPDATE `foo` SET `x`='y' WHERE `a`='b'
You can then run
SELECT `id` FROM `foo` WHERE `a`='b'
to fetch the updated id's.
Edit
I see you're using ON DUPLICATE KEY UPDATE.
You can modify your query to become (assuming id is the primary auto_increment key)
ON DUPLICATE KEY UPDATE
`url` = '".mysqli_real_escape_string($connection,$data['url'])."',
id = LAST_INSERT_ID(id)
Then you can use mysqli_insert_id() regardless of if it was an UPDATE or INSERT
For example, if I run (with a record of id=2 exists; so we'll update);
INSERT INTO foobar (id, foo) VALUES (2, 'bar') ON DUPLICATE KEY UPDATE foo = 'baz', id = LAST_INSERT_ID(id);
SELECT LAST_INSERT_ID();
The output is 2, as that was the last insert id.

Update query MySQL PHP

im trying to update my table using the following query...
$query = mysql_query("UPDATE `outgoings` (id, user_id, bill, bill_name, bill_description, bill_colour ) VALUES ('$id', '$uid', '$bill', '$billname', '$billdescription', '$billcolour') WHERE id = '$id'") or die(mysql_error());
It returns...
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 '(id, user_id, bill, bill_name, bill_description, bill_colour ) VALUES ('', '8464' at line 1
Ive tried removing ' around my variables and googling for alternative methods but cant seem to figutre out what imdoing wrong?
Use this syntax for update statements:
UPDATE `outgoings` set id = '$id', user_id = '$uid' ... where ...
You got it mixed with insert statement I guess.
It looks like your ID is empty (...VALUES ('',...). Should there be an ID there?
Your $id seems to be empty or not defined yet. Read mysql.error() up to the end.
The update query has different syntax, something like that:
UPDATE `outgoings` SET user_id='$uid', bill='$bill' WHERE id = '$id'

In PHP, when using PDO with pgSQL how to get the value of "RETURNING" clause in the original INSERT sql query

In PHP, I am using PDO with the pgSQL drivers. I wanted to know how to get the value of the "RETURNING" clause given in the INSERT sql query.
My current code looks like this,
$query = 'INSERT INTO "TEST" (firstname, lastname) VALUES ('John', 'Doe') RETURNING user_id';
$queryHandle = $connection->prepare($query);
$queryHandle->execute();
Obviously
$queryHandle->execute();
returns TRUE or FALSE. But I wanted to get the value of "user_id" if the insert was successful. Can you guys give me a pointer as to how to go about it? Thanks.
$ret = $queryHandle->fetchColumn();
Will return a single value instead of an array.
Did you tried to treat the command as a select returning, running
$ret=$queryHandle->fetchAll();
I am doing it like this (PHP 8.1.13, PostreSQL 15):
$query = "INSERT INTO test (firstname, lastname) VALUES ('John', 'Doe') RETURNING id";
$queryHandle = $connection->prepare($query);
$queryHandle->execute();
$last_id = $connection->lastInsertId('test_id_seq');
I took 'test_id_seq' from the following SQL, i.e. it is [table]_[column]_seq
CREATE TABLE IF NOT EXISTS public.test
(...
id integer NOT NULL DEFAULT 'nextval('test_id_seq'::regclass)',
CONSTRAINT test_pkey PRIMARY KEY (id)
)

Check if exists, if so, update by 1++, if not insert

Hey guys quick question, I currently have an insert statement
$query= "INSERT into new_mail VALUES ('$to1', '0')"; where fields are username, and message_number
Currently what I would do to check if the entry exists, is do a select query then check the number of rows with mysql_num_rows (php). If rows==1 then I get the current message_number and set it equal to
$row['message_number']+1.
Then I update that entry with another query.
Is there an easier way to do all this in just mysql with just one query (check if exists, if not insert, if so update message_number, increase by 1)?
Depending on how your table is structured, you may be able to use the ON DUPLICATE KEY UPDATE (link to the MySQL manual) feature of INSERT:
INSERT into new_mail VALUES ('$to1', '0') ON DUPLICATE KEY UPDATE message_number=message_number+1
Use INSERT...ON DUPLICATE KEY UPDATE. The MySQL manual has an example which does almost exactly what you need:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
To make this work you need to add a UNIQUE index on the column that you use to check for duplicates. There is one important warning though:
In general, you should try to avoid using an ON DUPLICATE KEY clause on tables with multiple unique indexes.
Got a little confused by your question and your table structures but I think you want something like this.
INSERT INTO new_mail (username, message_number)
VALUES ($username, $message_number)
ON DUPLICATE KEY UPDATE message_number=message_number + 1;
This is presuming username is your primary key (more likely something like userid). Hope this helps.
EDIT: The ON DUPLICATE KEY UPDATE answers are better, but you could do this (eludes the select query):
Assuming you're using the mysqli extenson:
$db = //Some construction of mysqli object;
$sql = 'UPDATE tablename SET RowValue = RowValue + 1 WHERE message_number = ?';
$updateStatement = $db->prepare($sql);
$updateStatement->bind_param('i', $message_number);
$message_number = //Set message number;
$updateStatement->execute();
if ($updateStatement->affectedRows == 0) {
$sql = 'INSERT INTO tablename (RowValue, message_number) VALUES (?, ?)';
$insertStatement = $db->prepare($sql);
$insertStatement->bind_param('ii', $rowValue, $messageNumber);
$rowValue = something;
$messageNumber = something;
$insertStatement->execute();
}

Categories