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();
}
Related
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
I have one simple function for delete account from my database. I have written it like below
public function removeAccount($email) {
$response = array('code' => 0, 'error' => false);
$stmt = $this->conn->prepare("SELECT id FROM user WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows) {
$user = $result->fetch_assoc();
$id = $user['id'];
$stmt->close();
$stmt = $this->conn->prepare("DELETE FROM number_list WHERE user_id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
$stmt = $this->conn->prepare("DELETE FROM number_status WHERE user_id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
$stmt = $this->conn->prepare("INSERT INTO old_user(email,serial,premium) SELECT email, device_id, membership FROM user WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
$stmt = $this->conn->prepare("DELETE FROM user WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
if ($stmt->affected_rows) {
$response["code"] = 1;
}
}
return $response;
}
Its giving me warning in below line
if ($stmt->affected_rows) {
I have searched way for solve it but does not getting idea whats wrong and what can fix it. Please check and let me know if someone can have idea about it. Thanks a lot.
$stmt = $this->conn->prepare("DELETE FROM user WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
if($stmt->affected_rows > 0) { $response["code"] = 1; }
$stmt->close();
In this case, we checked to see if any rows got updated. For reference, here's the usage for mysqli::$affected_rows return values.
-1 - query returned an error; redundant if there is already error handling for execute()
0 - no records updated on UPDATE, no rows matched the WHERE clause or no query has been executed
Greater than 0 - returns number of rows affected; comparable to mysqli_result::$num_rows for SELECT
You're trying to get the number of affected rows from a closed statement.
Instead of
$stmt->execute();
$stmt->close();
if ($stmt->affected_rows) {
$response["code"] = 1;
}
Use
$stmt->execute();
$num_affected_rows = $stmt->affected_rows;
$stmt->close();
if ($num_affected_rows) {
$response["code"] = 1;
}
There are many reasons for this error, but the one I had today was one I have not found documented anywhere.
I had two (2) copies of same virtual machine running and they were both competing in some way that I do not understand well enough to explain, but going into VirtualBox and shutting one of them off solved the problem.
I know this an obscure scenario, but if anyone else runs across the same I hope my answer stops them from wasting time on it like I did.
I have a database in which I have user_id & associated_id.There can be multiple associated_id for a single user_id. Now I want to fetch all the associated_ids into a single array. I have tried this method but don't know how to get them in array.
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = ?");
$stmt->bind_param("s", $user_id);
if ($stmt->execute())
{
while ($stmt->fetch())
{
//what to write here
}
//echo var_dump($user);
$stmt->close();
}
Try this:
$stmt = $mysqli->prepare("SELECT associated_id FROM my_contacts WHERE user_id = ?")) {
$stmt->bind_param('s', $user_id); // Bind "$user_id" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($associated_id);
$stmt->fetch();
The results will be stored in the $associated_id array.
You can bind parameters like this and use fetchall method to get all the results in a array
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = :user_id");
$stmt->bind_param(":user_id", $user_id, PDO::PARAM_INT);
if ($stmt->execute())
{
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
//echo var_dump($user);
$stmt->close();
}
According to your code you used mysqli.
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = ?");
if($stmt->execute()){
$result = $stmt->get_result();
if($result->nom_rows > 0){
while($row = $result->fetch_assoc()){
var_dump($row)
}
}else{
echo "Sorry NO data found";
}
}else{
echo "Some thing is wrong";
}
here you can't used $stmt->bind_result(); instead of use $stmt->get_result()
$stmt->bind_result(); is only used when you define field in select query
with * you need to used $stmt->get_result()
refer this link for more information
Example of how to use bind_result vs get_result
Sorry if I'm asking an already answered question, but I was not able to find my specific set-up.
I have a php file called functions.php, where I store all my functions and where I prepare my database.
A small example would be as follows:
function getUsers()
{
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("SELECT
id,
user_name,
FROM db_users");
$stmt->execute();
$stmt->bind_result($id, $user);
while ($stmt->fetch()){
$row[] = array('id' => $id, 'user_name' => $user);
}
$stmt->close();
return ($row);
}
I want to make a search function, with a form where I can search with OPTION VALUES, i.e values as: id, user_name.
By having functions.php I am already establishing the connection to the mysql database,
How can I search the database with my '%searchrequest%' with a search.php?
Or do you suggest another solution?
Just pass these search values into your current function. If nothing is passed,it will fetch all the data. If there is any value passed it will filter based on it.
function getUsers($id="",$user_name="")
{
global $mysqli,$db_table_prefix;
$query = "SELECT
id,
user_name,
FROM db_users WHERE 1 = 1 ";
if(trim($id))
$query .= " AND id = '".$id."'";
if(trim($user_name))
$query .= " AND user_name = '".$user_name."'";
$stmt = $mysqli->prepare($query);
$stmt->execute();
$stmt->bind_result($id, $user);
while ($stmt->fetch()){
$row[] = array('id' => $id, 'user_name' => $user);
}
$stmt->close();
return ($row);
}
I'm using MySQLi prepared statements to do this because the data is coming from other sources.
Here's my code it doens't work man. I don't understand why I need to do $stmt->store_result() in order to run num_rows().. Because If I don't run store_result, I would get an error:
Fatal error: Call to a member function bind_param() on a non-object
foreach($this->contents as $key => $dealer) {
foreach($dealer as $deals) {
$stmt = $mysqli->prepare("SELECT id, name FROM company WHERE name = ? LIMIT 1");
$stmt->bind_param("s", $deals['company']);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows() > 0) {
$companyid = // I don't know how to get the id from the query
} else {
$stmt->prepare("INSERT INTO company (name) VALUES (?)");
$stmt->bind_param("s", $deals['company']);
$stmt->execute();
}
$stmt->close();
}
}
Basically I want the code to check if the company already exists in the company table, then after checking it, if the company exists then I need to record the id of the company so i can use it in my other queries, but if it doesn't exists then I need to record the company name then get the id so i can use it in my other queries.
To get your $companyId you need to do $stmt->bind_result() and $stmt->fetch(). Docs on fetch()
if($stmt->num_rows() > 0) {
// To get your companyId
$stmt->bind_result($companyId);
$stmt->fetch()
// Now $companyId has the value from id in the database
} else {
// Do your insert statement, etc...
}