MySQLi prepared statements: insert increment of a value - php

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

Related

WHERE NOT EXISTS

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

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

Combine INSERT INTO SELECT, with DELETE at the same time

I have a button
<button onClick=sAve('save','."$id."']."')>SAVE</button>
Once I click it, I want to use AJAX to pass the parameters to the PHP page to perform the following task to MYSQL:
switch... case "Save":
$sql1 = "INSERT INTO permanent_table (id, user, email)
SELECT id, user, email
FROM temp_table WHERE id='".$_GET['id']."'";
$sql2 = "DELETE FROM temp_table WHERE id='".$_GET['id']."'";
Whereby permanent_table having same structure as temp_table. I tried to run both queries just like that but it is not working, so I guess that is not the right way.
In my case, my question is:
What is the real pro way to use PHP/sql to perform this task?
Is there any way I can simplify/combine it to a single query?
I think this is you want
<button onClick="$.post('/php file name/', {'save','."$id."'}, function(data){});">SAVE</button><br/>
Then you could run some query's in the PHP file.
$sql = $conn->prepare("INSERT INTO `permanent_table` (`id`, `user`, `email`) VALUES(?, ?, ?)";
$sql->bind_param("sss", $_GET['id'], "", "");
$sql->execute();
$sql = $conn->prepare("DELETE FROM `temp_table` WHERE `id`=?");
$sql->bind_param("s", $_GET['id']);
$sql->execute();
$sql = $conn->prepare("SELECT `id`, `user`, `email` FROM `temp_table` WHERE `id`=?");
$sql->bind_param("s", $_GET['id']);
$sql->execute();
//select last so that you can grab the results
Run them on your way (PDO or MYSQL)
I know a lot about query's so feel free to ask something to me!

Moving image from one SQL server table to another

I have two tables which store the same data. One is for active users and the other for inactive users. When a user comes, it is searched in the active table and if not found, it is searched in the inactive table. If the user info is found in the inactive table, then it should be moved to active table and deleted from inactive table.
The tables have a column that stores a photograph. When I try to insert the information to active table, I get the following error:
SQLSTATE[22018]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Operand type clash: nvarchar(max) is incompatible with image
I am sure it is caused by the photo because if the user info does not have a photo, the move is successful. But when there is a photo, it fails with the above error.
The SQL that creates the table:
CREATE TABLE [dbo].[tblBackup](
[Id] [int] IDENTITY(1,1) NOT NULL,
[DriverId] [int] NULL,
[FirstNameAmh] [nvarchar](100) NULL,
[FatherNameAmh] [nvarchar](100) NULL,
[GrandNameAmh] [nvarchar](100) NULL,
[Photo] [image] NULL
)
Here is the code:
$dbc->beginTransaction();
$sql = "select * from tblBackup where Id=?";
$stmt = $dbc->prepare($sql);
$stmt->bindParam(1, $_GET["gid"]);
$stmt->execute();
$row = $stmt->fetch();
$ins = "insert into tblActive(Id, DriverId, FirstNameAmh, FatherNameAmh, GrandNameAmh, Photo) values(?, ?, ?, ?, ?, ?)";
$st = $dbc->prepare($ins);
$val = array($row['Id'], $row['DriverId'], $row['FirstNameAmh'], $row['FatherNameAmh'], $row['GrandNameAmh'], $row['Photo']);
$st->execute($val);
$sql = "delete from tblBackup where Id=?";
$stmt = $dbc->prepare($sql);
$stmt->bindParam(1, $_GET["gid"]);
$stmt->execute();
$dbc->commit();
Edit:
I concluded that the photo data retrieved by PHP is being treated as nvarchar(max) type rather than image type by SQL server. Because of this, SQL server is complaining that it could not insert nvarchar(max) in image data type column. Is there a way to solve this?
If you are in the development phase, I think it would be better to create a stored procedure including "insert select" with "gid" as the parameter and execute it from php. Can't it be a solution for you?
I changed the code a little bit and now it is working. It is seems the problem is cause by prepared statement, though I don't understand why.
$dbc->beginTransaction();
$sql = "select * from tblBackup where Id=?";
$stmt = $dbc->prepare($sql);
$stmt->bindParam(1, $_GET["gid"]);
$stmt->execute();
$row = $stmt->fetch();
$ins = "insert into tblActive(Id, DriverId, FirstNameAmh, FatherNameAmh, GrandNameAmh, Photo) values(?, ?, ?, ?, ?, ".$dbc->quote($row['Photo']).")";
$st = $dbc->prepare($ins);
$val = array($row['Id'], $row['DriverId'], $row['FirstNameAmh'], $row['FatherNameAmh'], $row['GrandNameAmh']);
$st->execute($val);
$sql = "delete from tblBackup where Id=?";
$stmt = $dbc->prepare($sql);
$stmt->bindParam(1, $_GET["gid"]);
$stmt->execute();
$dbc->commit();

mysqli prepared statement - do not update NULL values

I have a prepared statement to update several fields. I get the data from a formular, but not all fields are required. So it's possible that some fields are not set. I set them default to NULL. Now I don't want to overwrite the old value by NULL. How can I tell MySql not to Update the value if it's NULL?
$insert_stmt = $mysqli->prepare("
UPDATE members SET username=?, email=?, $password=?, $random_salt=?, level=?, customerID=?, name=?, surname=?, phone=?, quantities=? WHERE id=?
");
$insert_stmt->bind_param('ssssissss', $username, $email, $password, $random_salt, $level, $customerID, $firstname, $surname, $phone);
$insert_stmt->execute();
In my case it's the password and random_salt value that could be NULL. It will be very bad to overwrite the password just by NULL ;)
You could change your query as follows:
UPDATE members SET
username = IFNULL(?, username),
email = IFNULL(?, email) -- and so on for all fields
WHERE...
It could also be more efficient to check the value of your parameters first, and build the query dynamically, including only fields for which you have a non-null value to update with.
You could try this:
$insert_stmt = $mysqli->prepare("UPDATE members SET username=?, email=?, password=IF(LENGTH('?')=0, password, '?'), random_salt=IF(LENGTH('?')=0, random_salt, '?'), level=?, customerID=?, name=?, surname=?, phone=?, quantities=? WHERE id=?");
the If condition translates to:
IF( < YOUR_CONDITION >, < VALUE_IF_TRUE >, < VALUE_IF_FALSE >).
Assuming id is PK you can use :
INSERT INTO members (
id,
username,
email,
password,
random_salt,
level,
customerID,
name,
surname,
phone,
quantities
) VALUES (
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?
) ON DUPLICATE KEY UPDATE
username = IF(username <> '',VALUES(username),username),
email = IF(email <> '',VALUES(email),email),
password = IF(password <> '',VALUES(password),password)
...
Read your query fields and data carefuly. Set of fields and set of data in bind are not match.
UPDATE members SET username=?, email=?, $password=?, $random_salt=?, level=?, customerID=?, name=?, surname=?, phone=?, quantities=? WHERE id=?
$insert_stmt->bind_param('ssssissss', $username, $email, $level, $customerID, $firstname, $surname, $phone);
Your bind list has no: password, random_salt, id

Categories