Unable to insert into MySQL database with php - php

In this Insert function where I have to insert a book into the database. The author is already existed in the database and I am trying insert a book that is written by the same author. What I am trying to achieve is to prevent user from entering the already existing author that would make duplicate data. When I get to the record the changelog with BookID but I get the a MySQL error where it says
"PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'SELECT BookID from book WHERE BookID = 102' for column 'BookID' at row 1 in C:\wamp64\www\bookprojectdb\Model\bookInsertFunction.php on line 97".
function addBook2($existauthor, $bt, $ot, $yop, $genre, $sold, $lan, $cip, $bp, $ps, $userID){
global $conn;
try {
$conn->beginTransaction();
//Author Data already exist
//Book Data
$stmt = $conn->prepare("INSERT INTO book(BookTitle, OriginalTitle, YearofPublication, Genre,
MillionsSold, LanguageWritten, CoverImagePath, AuthorID)
VALUES(:bt, :ot, :yop, :genre, :sold, :lan, :cip, :authorid);");
$stmt->bindValue(':bt', $bt);
$stmt->bindValue(':ot', $ot);
$stmt->bindValue(':yop', $yop);
$stmt->bindValue(':genre', $genre);
$stmt->bindValue(':sold', $sold);
$stmt->bindValue(':lan', $lan);
$stmt->bindValue(':cip', $cip);
$stmt->bindValue(':authorid',$existauthor);
$stmt->execute();
//BookPlot Data
$lastbookID = $conn->lastInsertID();
$stmt = $conn->prepare("INSERT INTO bookplot(Plot, PlotSource, BookID)
VALUES(:bp, :ps, :bookid);");
$stmt->bindValue(':bp', $bp);
$stmt->bindValue(':ps', $ps);
$stmt->bindValue(':bookid', $lastbookID);
$stmt->execute();
//Changelog Date Create Insert. This inserts date created, bookid and userid.
$datecreated = (date('y-m-d h:m:s'));
$bookID = "SELECT BookID from book WHERE BookID = $lastbookID";
$stmt = $conn->prepare("INSERT INTO changelog(DateCreated, BookID, UserID)
VALUES(:datecreated, :bookid, :userid);");
$stmt->bindValue(':datecreated', $datecreated);
$stmt->bindValue(':bookid', $bookID);
$stmt->bindValue(':userid', $userID);
$stmt->execute();
//commit
$conn->commit();
}
catch(PDOException $ex) {
$conn->rollBack();
throw $ex;
}
}
$existauthor
$query = $conn->prepare("SELECT Name, Surname, AuthorID FROM author WHERE Name = :name AND Surname = :surname");
$query->bindValue(':name', $name);
$query->bindValue(':surname', $surname);
$query->execute();
$row = $query->fetch();
if($query->rowCount() < 1){ //if author doesn't exists
addBook($name, $surname, $nationality, $yob, $yod,
$bt, $ot, $yop, $genre, $sold, $lan, $cip, $bp, $ps, $userID);
header('location:../View/Pages/adminView.php');
}else {
//if author exists
$existauthor = $row['AuthorID'];
addBook2($existauthor,$bt, $ot, $yop, $genre, $sold, $lan, $cip, $bp, $ps, $userID);
header('location:../View/Pages/adminView.php');
}
I thought that by using "lastinsertID();", it would have recorded ID of recently created book. Please Help !

'SELECT BookID from book WHERE BookID = 102' - that is an incorrect integer value indeed.
You have this value assigned to a variable:
$bookID = "SELECT BookID from book WHERE BookID = $lastbookID";
and then you're trying to bind it in place of an integer:
$stmt->bindValue(':bookid', $bookID);

Here's the help you need:
if(!$stmt->execute()) echo $stmt->error;
You ALWAYS should expect errors, and have a workaround, but first you need to check for errors

Related

INSERT INTO doesn't fill all rows

I have a problem with my code, it is PayPal express Integration. I mean in its original state after some tweaking to match my database and so on it works, it fills rows with ex. payerID and so on.
I have in my database 2 tables - first is Products it has 5 Rows, like productID, Price, currency and so on, but I need 1 extra row - let's say we call it Credits. I manually added it to my database, filled Table Products with data.
Then I have another table called Orders- where I added Row called Credits too, than after successful payment+checkout matched Credits to chosen Product it should fill this Row Credits in Orders table. The problem that I have it that Order Table is filled with all data except that last Row -> Credits it's always showing NULL in the database.
This is part of my code:
public function getAllProducts()
{
$db = getDB();
$stmt = $db->prepare("SELECT * FROM products");
$stmt->bindParam("pid", $pid, PDO::PARAM_INT) ;
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db=null;
return $data;
}
public function getProduct($pid)
{
$db = getDB();
$stmt = $db->prepare("SELECT * FROM products WHERE pid=:pid");
$stmt->bindParam("pid", $pid, PDO::PARAM_INT) ;
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_OBJ);
$db=null;
return $data;
}
and this where I have a problem
public function orders()
{
$id = $_SESSION['session_id'];
$db = getDB();
$stmt = $db->prepare("SELECT P.product, P.price, P.product_img, P.currency, P.credits, O.created, O.oid FROM orders O, products P WHERE O.id_fk=:id AND P.pid = O.pid_fk ORDER BY O.created DESC");
$stmt->bindParam("id", $id, PDO::PARAM_INT) ;
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db=null;
return $data;
}
public function updateOrder($pid, $payerID, $paymentID, $token, $credits)
{
$id = $_SESSION['session_id'];
if($this->pyamentCheck($paymentID) < 1 && $id > 0){
$db = getDB();
$stmt = $db->prepare("INSERT INTO orders (id_fk, pid_fk, payerID, paymentID, token, created, credits) VALUES (:id, :pid, :payerID, :paymentID, :token, :created, :credits)");
$stmt->bindParam("paymentID", $paymentID, PDO::PARAM_STR) ;
$stmt->bindParam("payerID", $payerID, PDO::PARAM_STR) ;
$stmt->bindParam("token", $token, PDO::PARAM_STR) ;
$stmt->bindParam("pid", $pid, PDO::PARAM_INT) ;
$stmt->bindParam("id", $id, PDO::PARAM_INT) ;
$created = time();
$stmt->bindParam("created", $created, PDO::PARAM_INT) ;
$stmt->bindParam(":credits", $credits, PDO::PARAM_INT) ;
$stmt->execute();
$db=null;
return true;
}
else{
return false;
}
}
I canĀ“t figure it out.
This is quite a frequent question so it deserves an answer, however obvious it may seem.
Once you have a working INSERT query and one of columns turns to be NULL, it means that the source variable contained NULL.
So the problem is neither with PDO, nor prepared statements, nor a database but simply with your source variable, $credits. You have to check your code related to this variable and make sure it does contain the desired value.

Update a field in a sql table with PHP

I have a table in my database that has the fields id, state, number and date.
What I need is to update the state of the record that matches the id that comes as a parameter.
I am doing the following but there is no result:
static public function mdlUpdateField($table, $id){
$stmt = Conection::conect()->prepare("UPDATE $table SET state = :state WHERE id = :id");
$stmt->bindParam(":state", "OK", PDO::PARAM_STR);
if($stmt -> execute()){
return "ok";
}else{
return "error";
}
$stmt -> close();
$stmt = null;
}
When I do it, I get the following error:
Fatal error: Uncaught Error: Cannot pass parameter 2 by reference
$stmt->bindParam(":state", "OK", PDO::PARAM_STR);
$stmt->bindParam(":id", $id, PDO::PARAM_INT);
and for pass the tale name you need dinamic sql
("UPDATE " . $table . " SET state = :state WHERE id = :id");
In this way you are at risk for sqlinjection ..

SQL insert into select issue

So i think i'm close to figuring this out but my query won't add the item from the "pending" table to the "items" table. can you guys help me out with this please. Also if i want it to delete after it gets added should i add the code below the INSERT INTO SELECT query? thanks
action.php:
$sql = "INSERT INTO items (photo,title,description, name) SELECT (photo,title,description, name) FROM pending";
$stmt = $conn->prepare($sql);
$stmt->execute();
Example for delete query after it takes the item from the "pending" into items:
$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT);
//try deleting record using the record ID we received from POST
$sql = "DELETE FROM pending WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $idToDelete, PDO::PARAM_INT);
$stmt->execute();
I think you are leaving yourself open to mistakes doing it this way.
Consider what would happen if a new row is added to the pending queue after you have issued the INSERT SELECT but before you have started your delete.
I think you need to do this in a more controlled way inside a single loop to make sure you are only deleting what you have copied from pending into items.
$sql = "SELECT photo,title,description, name FROM pending";
$select_pending = $conn->prepare($sql);
$select_pending->execute();
$sql = "INSERT INTO items (photo,title,description, name)
VALUES (:photo,:title,:description, :name)";
$insert_items = $conn->prepare($sql);
$sql = "DELETE FROM pending WHERE id = :id";
$delete_pending = $conn->prepare($sql);
// only if you are using INNODB databases.
//$conn->beginTransaction();
while( $row = $select_pending->fetch_object() ) {
$insert_items->bindParam(':photo', $row->photo, PDO::PARAM_STR);
$insert_items->bindParam(':title', $row->title, PDO::PARAM_STR);
$insert_items->bindParam(':description', $row->description, PDO::PARAM_STR);
$insert_items->bindParam(':name', $row->name, PDO::PARAM_STR);
$insert_items->execute();
$delete_pending->bind_param(':id', $row->id, PDO::PARAM_INT);
$delete_pending->execute();
}
// only if you are using INNODB databases.
//$conn->commit();
$sql = "INSERT INTO items (photo,title,description, name)
SELECT photo,title,description, name FROM pending";
remove the () in the SELECT statement.

Add data into two table connected with id

Hi here I have this code to insert data to mysql database into table radnici :
try {
$STH = $db->prepare("INSERT INTO radnici (ime_prezime, jmbg, grad, ulica, posta, telefon, uloga, email, user_id) VALUES (:1,:2,:3,:4,:5,:6,:7,:8,:9)");
$STH->bindParam(':1', $_POST['ime']);
$STH->bindParam(':2', $_POST['jmbg']);
$STH->bindParam(':3', $_POST['grad']);
$STH->bindParam(':4', $_POST['ulica']);
$STH->bindParam(':5', $_POST['posta']);
$STH->bindParam(':6', $_POST['telefon']);
$STH->bindParam(':7', $_POST['pozicija']);
$STH->bindParam(':8', $_POST['email']);
$STH->bindParam(':9', $user_id);
//HERE I NEED TO INSERT DATA TO TABLE WORKHOURS BUT CONNECTED WITH JUST ADDEDED ID
//SO here I NEED query something like this // INSERT INTO radnici (ID, ID_radnici, ime_prezime, jmbg,... here ID_radnici is =with ID from table radnici of added data
$STH->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
echo "<p>Data submitted successfully</p>";
So now when I add this I need to add into this table workhours data but connected with ID with just added data...
so in second table I have: ID, ID_radnici (here I must add ID_radnici same value as ID on table radnici), value, user_id
I write this but DONT work:
UPDATE:
try {
$STH = $db->prepare("INSERT INTO radnici (ime_prezime, jmbg, grad, ulica, posta, telefon, uloga, email, user_id) VALUES (:1,:2,:3,:4,:5,:6,:7,:8,:9)");
$STH->bindParam(':1', $_POST['ime']);
$STH->bindParam(':2', $_POST['jmbg']);
$STH->bindParam(':3', $_POST['grad']);
$STH->bindParam(':4', $_POST['ulica']);
$STH->bindParam(':5', $_POST['posta']);
$STH->bindParam(':6', $_POST['telefon']);
$STH->bindParam(':7', $_POST['pozicija']);
$STH->bindParam(':8', $_POST['email']);
$STH->bindParam(':9', $user_id);
$orderID = $db -> lastInsertId();
$STH1 = $db->prepare("INSERT INTO workhours (ID_radnika) values($orderID)"); // where $value is the value you want to insert...
$STH->execute();
$STH1->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
echo "<p>Data submitted successfully</p>";
Using lastInsertId will do what you want:
$orderID = $db -> lastInsertId();
Use lastInsertId() and insert your data into the other table using the value returned from it.
Something like this:
int $lastID = $db->lastInsertId();
if ( $lastID ) {
$STH = $db->prepare("INSERT INTO workhours (ID_radnici, value, userid) values($lastID, $value, $user_id)"); // where $value is the value you want to insert...
$STH->execute();
}

Problem with mysqli fetch

I'm having a mysqli data fetching problem. I will try to explain my problem by example:
I want to fetch entries (by different persons), from a table. Now I want to look for each of the fetched person's name in another table and see if he has any photo.
My code is given below, however its not working, I'm getting following errors:
mysqli::prepare() [mysqli.prepare]: All data must be fetched before a new statement prepare takes place
Call to a member function fetch() on a non-object in ...
My Code:
if ($stmt = $this->mysqli->prepare("SELECT entry, author, time FROM messages WHERE user = ?")) {
$stmt->bind_param("s", $user_name);
$stmt->execute();
$stmt->bind_result($entry, $author, $time);
while ($stmt->fetch()) {
if ($stmt = $this->mysqli->prepare("SELECT photo_id FROM photos WHERE user = ?")) {
$stmt->bind_param("s", $author);
$stmt->execute();
$stmt->bind_result($photo_id);
}
//echo $photo_id;
}
$stmt->close();
}
I'll be very thankful for any help.
Assign the second statement to new variable so it wouldn't override the first variable and cause the "all data must be fetched.." error.
if ($stmt = $this->mysqli->prepare("SELECT entry, author, time FROM messages WHERE user = ?")) {
$stmt->bind_param("s", $user_name);
$stmt->execute();
$stmt->bind_result($entry, $author, $time);
while ($stmt->fetch()) {
if ($st = $this->mysqli->prepare("SELECT photo_id FROM photos WHERE user = ?")) {
$st->bind_param("s", $author);
$st->execute();
$st->bind_result($photo_id);
}
//echo $photo_id;
$st->close();
}
$stmt->close();
}

Categories