Please How can i use prepared statement to update one table and insert into another table. i did what i no was right but the when i submit the form on that page, it just give me a blank page and nothing happened in the two database see what it look like
$check = "INSERT INTO users(userEmail, password, joinDate, recEmails,
isActive, hash, lastUpdated)
VALUES (?, ?, NOW(), 1, 0, ?, NOW() ) ";
$stmt = $mysqli->prepare($check);
$stmt->bind_param('sss',$emailAddy,$password,$hash );
$stmt->execute();
$stmt->close();
$check1="UPDATE pin SET status = '1', usedby = ?,WHERE pin = ?";
$stmt = $mysqli->prepare($check1);
$stmt->bind_param('ss',$emailAddy,$pin);
$stmt->execute();
$stmt->close();
The result i get is this example.com is currently unable to handle this request.
I have tried and discovered that the issue is hidden somewhere here, if i remove the update table instruction the code works fine but one i return the issue comes back. Please can anybody help?
You have an error here:
$check1 = "UPDATE pin SET status = '1', usedby = ?, WHERE pin = ?";
Change it to (Remove the , after usedby = ?)
$check1 = "UPDATE pin SET status = '1', usedby = ? WHERE pin = ?";
Related
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();
Ok .. Here is the thing. I want to list users logged on and change their status when logged out. This works perfect. I created a table for that called tblaudit_users. The existing users I SELECT from a tbl_users table.
What I want, is that if an user already exists in the tblaudit_users table it will UPDATE the LastTimeSeen time with NOW(). But instead of updating that record, it creates a new record. This way the table will grow and grow and I want to avoid that. The code I use for this looks like:
+++++++++++++++++++
$ipaddress = $_SERVER['REMOTE_ADDR'];
if(isset($_SESSION['id'])){
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
$achternaam = $_SESSION['achternaam'];
$district = $_SESSION['district'];
$gemeente = $_SESSION['gemeente'];
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE username = '{$username}' AND active = '1' LIMIT 1");
$query->execute();
foreach($query->fetchAll(PDO::FETCH_OBJ) as $value){
$duplicate = $value->username;
}
if($duplicate != 1){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
");
$insert->execute();
} elseif($duplicate = 1){
$update = $db->prepare("UPDATE tblaudit_users SET LastTimeSeen = NOW(),status = '1' WHERE username = '{$username}'");
$update->execute();
} else {
header('Location: index.php');
die();
}
}
I am lost and searched many websites/pages to solve this so hopefully someone here can help me? Thanks in advance !!
UPDATE:
I've tried the below with no result.
+++++
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
ON DUPLICATE KEY UPDATE set LastTimeSeen = NOW(), status = '1'
");
$insert->execute();
Ok. I altered my query and code a little:
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE username = '{$username}' LIMIT 1");
$query->execute();
if($query){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
ON DUPLICATE KEY UPDATE set LastTimeSeen = NOW(), status = '1'
");
$insert->execute();
} else {
header('Location: index.php');
die();
}
}
I also added a UNIQUE key called pid (primary id). Still not working.
Base on http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html, don't use 'set' in update syntax
example from the page:
INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=9;
Several issues:
You test on $query, but that is your statement object, which also will be valid even if you have no records returned from the select statement;
There can be issues accessing a second prepared statement before making sure the previous one is closed or at least has all its records fetched;
There is a syntax error in the insert statement (set should not be there);
For the insert ... on duplicate key update to work, the values you provide must include the unique key;
SQL injection vulnerability;
Unnecessary split of select and insert: this can be done in one statement
You can write your test using num_rows(). To get a correct count call store_result(). Also it is good practice to close a statement before issuing the next one:
$query = $db->prepare("SELECT * FROM tblaudit_users
WHERE username = '{$username}' LIMIT 1");
$query->execute();
$query->store_result();
if($query->num_rows()){
$query->close();
// etc...
However, this whole query is unnecessary when you do insert ... on duplicate key update: there is no need to first check with a select whether that user actually exists. That is all done by the insert ... on duplicate key update statement.
Error in INSERT
The syntax for ON DUPLICATE KEY UPDATE should not have the word SET following it.
Prevent SQL Injection
Although you use prepared statements (good!), you still inject strings into your SQL statements (bad!). One of the advantages of prepared statements is that you can use arguments to your query without actually injecting strings into the SQL string, using bind_param():
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district,
gemeente, ipaddress, LastTimeSeen, status)
VALUES (?, ?, ?, ?, ?, ?, NOW(), '1')
ON DUPLICATE KEY UPDATE LastTimeSeen = NOW(), status = '1'
");
$insert->bind_param("ssssss", $userId, $username, $achternaam,
$district, $gemeente, $ipaddress);
$insert->execute();
This way you avoid SQL injection.
Make sure that user_id has a unique constraint in the tblaudit_users. It does not help to have another (auto_increment) field as primary key. It must be one of the fields you are inserting values for.
The above code no longer uses $query. You don't need it.
I found the issue
if(isset($_SESSION['id'])){
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
$achternaam = $_SESSION['achternaam'];
$district = $_SESSION['district'];
$gemeente = $_SESSION['gemeente'];
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE user_id = '{$userId}' LIMIT 1");
$query->execute();
if($query->rowcount()<1){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
");
$insert->execute();
} elseif($query->rowcount()>0) {
$update = $db->prepare("UPDATE tblaudit_users SET LastTimeSeen = NOW(),status = '1' WHERE user_id = '{$userId}'");
$update->execute();
} else {
header('Location: index.php');
die();
}
}
Instead of using $username in my query, I choose $userId and it works.
So, I have problem with inserting data into 2 tables directly using subquery and last insert id.
i have following codes
if (isset($_POST['recipient']))
$recipient = sanitize($_POST['recipient']);
if (isset($_POST['message']))
$message = sanitize($_POST['message']);
$sql = "INSERT INTO message (senderID, message)
VALUES (?,?)";
if ($stmt = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt, "is", $userID, $message);
mysqli_stmt_execute($stmt);
$newID = mysqli_insert_id($connection);
$sql2 = "INSERT INTO message_recipient (messageID, recipientID)
SELECT ?, userID
from user
where username = $recipient";
if ($stmt2 = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt2, "ii", $newID, $recipient);
mysqli_stmt_execute($stmt2);
mysqli_stmt_close($stmt2);
}
}
for the $stmt2 ,it works well in phpmyadmin, but without the prepared statement. The first query works well, it can add data, but can't the second. Also, i dont know why the first query will insert 2 data, with first data correct and second false.
Is the way i get last insert id wrong, or my second query is false?
Any help given really appreciated. thank you so much
Thanks in advance for everyone's help. I have an issue that has driven me crazy for hours. I've tried writing this several times using several methods with full error checking. I've tried single quotes on the field names, I've tried putting an SQL query in a variable and passing it to $db->prepare -- all to no avail. I've checked my permissions and everything looks good to me. I'm sure it's something simple but I'm bleary-eyed going over this and I'm just not seeing it.
$db = OpenDBConn();
// $query = "UPDATE agent_profiles SET ";
// $query .= "website = ?, display_email = ?, primary_phone = ?, secondary_phone = ?, secondary_phone_type = ?, ";
// $query .= "address_1 = ?, address_2 = ?, city = ?, state = ?, zip = ?, country = ?, description = ? ";
// $query .= "WHERE agent_id = ?";
$stmt = $db->prepare("UPDATE agent_profiles SET
website=?,
display_email=?,
primary_phone=?,
secondary_phone=?,
secondary_phone_type=?,
address_1=?,
address_2=?,
city=?,
state=?,
zip=?,
country=?,
description=?
WHERE agent_id=?");
$stmt->bind_param('ssssssssssssi', $this->website, $this->display_email, $this->primary_phone, $this->secondary_phone, $this->secondary_phone_type, $this->address_1, $this->address_2, $this->city, $this->state, $this->zip, $this->country, $this->description, $this->agent_id);
$stmt->execute();
$stmt->close();
$db->close();
Even with full error reporting and modifying the code to look for $db->error, it all looks and runs clean but doesn't save to the table. Functions used here are used in other places and work fine. Any guesses?
error_reporting(-1);
ini_set('display_errors', 'On');
Is your friend, why do you always exclude him on your journeys?
I'm trying to update a table in PHP with SQLite. My code is the following:
//Get params like this
$title = $_POST['title'];
...
$params = array($visible, $link, $title, $post, $month, $day, $year, $sub3);
$query = "UPDATE posts SET visible = ?, link = ?, title = ?, entries = ?, month = ?, day = ?, year = ? WHERE id = ?; COMMIT;";
$stmt = $db->prepare($query);
$result = $stmt->execute($params);
If I get the values from $_POST, by the time it does the execute on the statement, 99% of the time, null values are updated in the fields instead of the $_POST data ($sub3 is not from $_POST).
If I hard code the values, it works fine. I also have an insert statement in the same code path (checks to see if it's new data first, if not do the INSERT). Insert works fine every time (data from $_POST).
Also, I have code like this for three other tables, all of which work. This is the only table that doesn't. Nothing different about set up of table compared to others.
This one works on a different table:
$params = array($name, $username, $email, $level, $sub3);
$query = "UPDATE users SET name = ?, username = ?, email = ?, level = ? WHERE id = ?; COMMIT;";
$stmt = $db->prepare($query);
$result = $stmt->execute($params);
I've tried bindParam, bindValue, and creating the statement string manually without prepare, but as long as it's from $_POST, it won't work.
What am I missing? Anything else I can try?
Print the POST variables and check if it has the right data.
print_r($_POST);
EDIT:
Change the query.
//$params = array($visible, $link, $title, $post, $month, $day, $year, $sub3);
$query = "UPDATE posts SET visible = '$visible', link = '$link', title = '$title', entries = '$entries', month = '$month', day = '$day', year = '$year' WHERE id = $id; COMMIT;";
Make sure you have the correct $id