Trouble Updating a Database Record - php

Here is prepare update statement and I think I Have the Variable types out of whack, not sure.
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE `Calibration_and_Inspection_Register` SET `item_type` = ?, `location` = ?, `date_last_test` = ?, `serial_number` = ?, `date_next_test` = ?, `comments` = ?
WHERE `id`=?"))
{
$stmt->bind_param("issdsds",`$id`, `$item_type`, `$location`, `$date_last_test`, `$serial_number`, `$date_next_test`, `$comments`);
$stmt->execute();
$stmt->close();
}

Order is important if you are not using named parameters. Since id is last parameter in the statement, it needs to be the last in the list of bound parameters as well.
Back-ticks around your parameter variables names in bind_param() call are also probably giving you errors. It should look like this:
$stmt->bind_param("ssdsdsi",$item_type, $location, $date_last_test, $serial_number, $date_next_test, $comments, $id);

Related

Prevent Duplicate Entries in PHP MySQL

I have the following in my PHP.
$stmt = $conn->prepare("INSERT IGNORE INTO savesearch (user, searchedFor, sortOrder, buildURLString, aspectFilters, oneSignalId, totalEntries)
VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $user, $searchedFor, $sortOrder, $buildURLString, $aspectFilters, $oneSignalId, $totalEntries);
// set parameters and execute
$user = $_POST['user'];
$searchedFor = $_POST["searchedFor"];
$sortOrder = $_POST["sortOrder"];
$buildURLString = $_POST["buildURLString"];
$aspectFilters = $_POST["aspectFilters"];
$oneSignalId = $_POST["oneSignalId"];
$totalEntries = $_POST["totalEntries"];
if ($stmt->execute()) {
$output->success = true;
echo json_encode($output);
} else {
$error->error = mysqli_error($conn);
echo json_encode($error);
}
However, IGNORE is not being picked up, it continues to add entries. Is there another good way to fix this?
Id like to see if the USER and the URL is the same, dont add, echo duplicate entry.
IGNORE is actually mostly for the opposite of what you want here. Instead, you can amend your MySQL table something like:
ALTER TABLE savesearch ADD UNIQUE KEY(user, buildURLString)
Then remove your IGNORE keyword

How to perform the following insert, mysql

I have two tables, reports and events, each table has a unique identifier called id with Auto increment, the problem is that the id in each table is not the same because a report can have events but maybe not. I would like to make a double insert but one column in each table must have an unique key. I do this with the following function:
function addactioneventuser(){
try {
$this->conn->beginTransaction();
$query = "INSERT INTO
" . $this->table_name . "
SET
case_id = ?,
from_to = 0,
action_id = ?,
accepted = 0,
message = ?";
// prepare query statement
$stmt = $this->conn->prepare($query);
// bind values
$stmt->bindParam(1, $this->case_id);
$stmt->bindParam(2, $this->action_id);
$stmt->bindParam(3, $this->message);
// execute the query
$stmt->execute();
// insert event query
$query2 = "INSERT INTO event_case
SET
title = ?, body = ?, class = ?, start = ?, end = ?, case_id= ?, worker_id = ?";
// prepare query statement
$stmt = $this->conn->prepare($query2);
// bind values
$stmt->bindParam(1, $this->title);
$stmt->bindParam(2, $this->body);
$stmt->bindParam(3, $this->class_event);
$stmt->bindParam(4, $this->start);
$stmt->bindParam(5, $this->end);
$stmt->bindParam(6, $this->case_id);
$stmt->bindParam(7, $this->worker_id);
// execute the query
$stmt->execute();
$this->conn->commit();
return true;
} catch (Exception $e) {
$stmt->rollBack();
return false;
}
}
The two inserts works perfectly but my problem is that the two ids for each table are not the same and as a consequence I can not delete at the same time an specific record from both tables and I don't know how to do it. I read about Cascade and other possible solutions but none of them seem pausible for my problem. I don't mind to create another column to use it as reference for both tables but I don't know how to do it in the above query.
Thank you in advance
Last insert id is $this->conn->insert_id;
You can get it after the operation and use the identifier.
For example to add it to the desired table

Insert into table with prepared statement

I'm trying to insert data from a form into a database using PHP and Mysqli but I can't get it working! My database has 4 fields: DATE, TITLE, CONTENT, ID. The ID field is auto-increment.
I've checked the connection and that's working fine. I've also echoed the form field values and the $blogDate variable I created, they're all fine too.
Here's my prepared statement:
if ($newBlog = $mysqli->prepare('INSERT INTO Blog VALUES ($blogDate, $_POST["bTitle"], $_POST["bContent"])')) {
$newBlog->execute();
$newBlog->close();
}
It's just not inserting the values into my table.
You are generating SQL containing strings that are not quoted or escaped.
Don't insert the data directly into the SQL string, use placeholders (?) and then bind the parameters before executing.
$query = "INSERT INTO Blog VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $blogDate, $_POST["bTitle"], $_POST["bContent"]);
$stmt->execute();
Since you are aware about prepared statement:
$newBlog = $mysqli->prepare('INSERT INTO Blog (`dateCol`, `titleCol`, `contentCol`) VALUES (?, ?, ?)');
$newBlog->bind_param( 'sss', $blogDate, $_POST["bTitle"], $_POST["bContent"] );
$newBlog->execute();
$newBlog->close();
since you are using auto increment field you need to specify column name and then values
try this code
$query = "INSERT INTO Blog (colname_1,colname_2,colname_3) VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $blogDate, $_POST["bTitle"], $_POST["bContent"]);
$stmt->execute();

SQL INSERT bind not working

When I call the function updatePost($postID, $postTitle, $postContent, $catID) it calls it but fails on the first line $stmt = db::connect()->prepare. I am accessing my database the same way for all other functions but this one is failing. Why?
function updatePost($inPostID, $inPostTitle, $inPostContent, $inCatID)
{
var_dump($stmt);
$stmt = db::connect()->prepare("UPDATE Posts SET postTitle = ?, postContent = ?, postCatID = ?, WHERE postID = ?");
var_dump($stmt);
$stmt->bind_param('ssii', $inPostTitle, $inPostContent, $inPostCatID, $inPostID);
$stmt->execute();
$stmt->close();
}
Lose the last comma in your SQL statement:
UPDATE Posts SET postTitle = ?, postContent = ?, postCatID = ? WHERE postID = ?

Get last insert id after a prepared insert with PDO

I'm using PHP PDO with PostgreSQL for a new project.
Given the following function, how can I return the id of the row just inserted?
It doesn't work the way it looks now.
function adauga_administrator($detalii) {
global $db;
$ultima_logare = date('Y-m-d');
$stmt = $db->prepare("INSERT INTO site_admins (sa_nume, sa_prenume, sa_user_name, sa_password, sa_email, sa_id_rol, sa_status, sa_ultima_logare) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bindParam(1, $detalii['nume']);
$stmt->bindParam(2, $detalii['prenume']);
$stmt->bindParam(3, $detalii['username']);
$stmt->bindParam(4, md5(md5($detalii['parola'] . SIGURANTA_PAROLE) . SIGURANTA_PAROLE));
$stmt->bindParam(5, $detalii['email']);
$stmt->bindParam(6, $detalii['rol'], PDO::PARAM_INT);
$stmt->bindParam(7, $detalii['status'], PDO::PARAM_INT);
$stmt->bindParam(8, $ultima_logare);
$stmt->execute();
$id = $db->lastInsertId();
return $id;
}
From the Manual:
Returns the ID of the last inserted
row, or the last value from a sequence
object, depending on the underlying
driver. For example, PDO_PGSQL()
requires you to specify the name of a
sequence object for the name
parameter.
It should be something like:
return $db->lastInsertId('yourIdColumn');
[EDIT] Update link to doc
From the PHP manual:
For example, PDO_PGSQL() requires you
to specify the name of a sequence
object for the name parameter.
You could also use RETURNING in the INSERT-statement and fetch the INSERT-result like a SELECT result.
Previous answers are not very clear (PDO doc too)
In postgreSQL, sequences are created when you are using the SERIAL data type.
CREATE TABLE ingredients (
id SERIAL PRIMARY KEY,
name varchar(255) NOT NULL,
);
So the sequence name will be ingredients_id_seq
$db->lastInsertId('ingredients_id_seq');

Categories