WHERE NOT EXISTS - php

I have a simple table with two columns "referralID" & "studentID"
I can add like this
$stmt = $pdo->prepare('INSERT INTO referralStudents (referralID,studentID) VALUES (?, ?)');
$stmt->execute([$myID,$studentID]);
I'm trying to get the WHERE NOT EXISTS statement to work. If there is already a row with both "referralID" & "studentID" don't add.
Both of these don't work can you show me where I'm going wrong?
$stmt = $pdo->prepare('INSERT INTO referralStudents (referralID,studentID) VALUES (?, ?) WHERE NOT EXISTS (SELECT * FROM referralStudents WHERE referralID = ? and studentID = ?")');
$stmt->execute([$myID,$studentID,$myID,$studentID]);
$stmt = $pdo->prepare('INSERT INTO referralStudents (referralID,studentID) VALUES (?, ?) WHERE NOT EXISTS (referralID,studentID) VALUES (?, ?)');
$stmt->execute([$myID,$studentID,$myID,$studentID]);

You need a SELECT statement and not VALUES to apply the conditions of the WHERE clause:
INSERT INTO referralStudents (referralID,studentID)
SELECT ?, ?
FROM dual
WHERE NOT EXISTS (SELECT * FROM referralStudents WHERE referralID = ? and studentID = ?)
You may remove FROM dual if your version of MySql is 8.0+.
See a simplified demo.

If the fields are empty i bet they are NULL. A field filled with NULL is existing but its content is NULL (NULL doesnt mean empty or non existing). Maybe this is what you need:
INSERT INTO refferalStudents (refferalID, studentID) VALUES (?,?) WHERE refferalID IS NULL AND studentID IS NULL

Related

Update already existing values while adding new ones

I'm inserting some values into my database.
$stmt = $conn->prepare("INSERT INTO `members` (`id`, `name`, `nickname`, `prefix`, `suffix`) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss",$row['member_id'], $row['name'], $row['nickname'], $row['prefix'], $row['suffix']);
$stmt->execute();
This does what I want: if a new user has joined this will add them to members. However, if an already existing member has changed their nickname this info doesn't get updated. I would like to 1) add new members like it currently does but also 2) update the nicknames for already existing members if there are any changes.
I tried adding the following code after the one above (first add members and then update) but it doesn't seem to work as I wanted.
$stmt = $conn->prepare("UPDATE members SET nickname = '?' WHERE id = '?'");
$stmt->bind_param("ss",$row['nickname'], $row['id']);
$stmt->execute();
You can use REPLACE INTO instead of INSERT INTO
Your prepare() would have
REPLACE INTO `members` (`id`, `name`, `nickname`, `prefix`, `suffix`) VALUES (?, ?, ?, ?, ?)
REPLACE updates the new data if the primary key value already exists.
More details here: https://dev.mysql.com/doc/refman/5.5/en/replace.html

Issue On Inserting Auto Incremented ID in MySQL Using Prepared Statement

I have table in MySQL database called MyGuests which has 4 fields as : id (PK and Auto Increment), name,age and email. I am using following code to insert data from user input form to the database:
<?php
$sql = mysqli('localhost','user','password','database');
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
$query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (?, ?, ?, ?)");
$query->bind_param("isis",$name,$age,$email);
$query->execute();
?>
now I am confused how to insert value for id which is auto incremented field using the Prepared statement! As you can see I passed 4 parameters as (?, ?, ?, ?) for data entry and used the "isis" for bind_param(); but not sure what must put in $name,$age,$email for id?
Can you please help me to figure this out?
Thanks
Just omit the id in the query i.e.
INSERT INTO MyGuests ( name, age, email) VALUES (?, ?, ?)
It will automatically add the incremented id, hence the name :)
one more option is supplying null value to the auto-increment column:
ie.
instead of $query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (?, ?, ?, ?)"); use $query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (null, ?, ?, ?)");

MySQLi prepared statements: insert increment of a value

Is it possible in any way to insert an increment of a certain column value ?
$stmt->$this->mysqli->prepare('INSERT INTO `users` ( `email`,`date_added`,`playCount`) VALUES ( ?, NOW(), ? )');
$stmt -> bind_param('si',$email, WHAT); // playCount++ somehow ...
$stmt -> execute();
I know I can use UPDATE to do that, but then I need to check if user exists first and then do INSERT and afterward UPDATE just for one column? There should be a better approach I think?
EDIT: UPDATE also won't work (won't prepare successfully-returns false: any ideas what might be wrong?)
$stmt = $this->mysqli->prepare('UPDATE `users` SET `newsletter` = ?, `date_last` = NOW(), points=points+?, WHERE `email` = ?');
(reference)
"INSERT INTO users ( `email`,`date_added`,`playCount`)
VALUES ( ?, NOW(), (SELECT MAX(playCount) from users)+1 );"

Insert auto-incremented ID using prepared statements

When inserting a new record into a table with an auto-incrementing ID column, it is normally enough to give the ID field the value NULL or omit it from the INSERT query, as explained at How to insert new auto increment ID
INSERT INTO `database`.`table` (`id`, `user`, `result`) VALUES (NULL, 'Alice', 'green')");
or
INSERT INTO `database`.`table` (`user`, `result`) VALUES ('Alice', 'green')");
My question is - how do you do the same thing when using prepared statements. I have tried the following, using NULL:
$stmt = $db->prepare("INSERT INTO `db` (id, name, password, text) VALUES (NULL, ?, ?, ?)");
$stmt->bind_param('sss', $name, $password, $text);
$stmt->execute();
and the fowllowing, omitting the ID field:
$stmt = $db->prepare("INSERT INTO `test_db` (name, password, text) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $name, $password, $text);
$stmt->execute();
When I run this I get nothing inserted and no error message in the browser. I think it is because it is trying to insert a duplicate value for the ID field (stackoverflow.com/questions/12179770/…) - but why it should do that when this seems equivalent to the non-prepared-statement way of inserting data, and then give no message, I'm not sure.
Any ideas most welcome!

INSERT INTO.....SELECT FROM

i want to put calory as the first value of fruits, i couldn't do it, can anyone help?
$sql = 'INSERT INTO fruits VALUES('', ?, ?, ?)'
SELECT calory
FROM diet
WHERE fruit = ?
';
$this->db->query($sql, array($a, $b, $c, $d));
The correct syntax is :
INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM "table2"
in your case this should be :
INSERT INTO fruits (calory)
SELECT calory
FROM diet
WHERE fruit = ?
(if "calory" is the name of the column in the table "fruits")
You can't mix up INSERT ... SELECT and INSERT ... VALUES in one query. Just select the other values as constants in your SELECT statement and you'll be fine:
INSERT INTO fruits
SELECT calory, ?, ?, ?
FROM diet
WHERE fruit = ?
This
INSERT INTO fruits SELECT calory, ?, ?, ? FROM diet WHERE fruit = ?
should do it...
When you use placeholders for values, (in your case the question marks) you need to use ->prepare() and not ->query(). Also your SQL syntax is completely wrong.
At a guess I think your query should read something like...
$sql = "INSERT INTO fruits VALUES('', ?, ?, ?) WHERE fruit = ?"; // Create query string.
$sth = $this->db->prepare($sql); // Prepare the query.
$sth->bindValue(1,$a); // Bind question marks to values
$sth->bindValue(2,$b); // (I am assuming that a,b,c,d are in
$sth->bindValue(3,$c); // the correct order...
$sth->bindValue(4,$d);
$sth->execute(); // Execute the query to insert the data.
You mean you need to put the answer of select query into insert query ,please try this
$sql = 'INSERT INTO fruits VALUES('(SELECT calory
FROM diet
WHERE fruit = ?)', ?, ?, ?)'
';

Categories