mysqli returning null values - php

im trying to get data from my DB but all i get is null values.
I know that the query isnt empty because i get values from inside my if($stmt->num_rows > 0)
code.
When i run my query on my phpmyadmin i also get good results.
This is my code thanks for helping:
$sql = "SELECT register_date FROM personal WHERE user_id = ?";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error."[$sql]");
$stmt->bind_param('s', $user_id);
$user_id = $_GET['user_id'];
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($register_date);
if($stmt->num_rows > 0)
{
$response["date"] = $register_date;
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else
{
$response["success"] = 0;
echo json_encode($response);
}

Try
$stmt->bind_result($register_date);
$stmt->execute();
$stmt->store_result();
$stmt->fetch();
echo $register_date;
Please read bind_result doc

Your code is a bit mixed up, you'll need to define your variables (in this case $user_id) before using them.
I suggest moving to PDO rather than using MySQLi.

Related

Property access is not allowed yet in

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.

Converting mysql functions to mysqli prepared statment keeping the same output

I'm currently going thorough a site and replacing all the functions which used to return mysql_fectch_array() results, which are put into while loops elsewhere. I'm trying to make them return the same data in the same format but by using mysqli prepared statements output. I have been successful with the code below in producing the same formatted output for single row results.
public function get_email_settings(){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT * FROM email_setting WHERE user_id = ? LIMIT 1");
$stmt->bind_param("i", $this->user);
$stmt->execute();
$stmt->bind_result(
$row['email_id'],
$row['user_id'],
$row['news'],
$row['new_message'],
$row['new_friend'],
$row['rule_assent'],
$row['agreement_ready'],
$row['agreement_all_assent'],
$row['time_cap'],
$row['donations']
);
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $row;
}
But how can I get this code to work when it returns more than one row? I want it to be produce the same result as if I had written:
return mysql_fetch_array($result);
Is it possible?
Consider the following adjustment, passing query results into an associative array:
public function get_email_settings(){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT email_id, user_id, news, new_message,
new_friend, rule_assent, agreement_ready,
agreement_all_assent, time_cap, donations
FROM email_setting
WHERE user_id = ? ");
$stmt->bind_param("i", $this->user);
$stmt->execute();
// CREATE RETURN ARRAY
$row = [];
// OBTAIN QUERY RESULTS
$result = $stmt->get_result();
// ITERATE THROUGH RESULT ROWS INTO RETURN ARRAY
while ($data = $stmt->fetch_assoc()) {
$row[] = $data;
}
$stmt->close();
return $row;
}
You will notice I explicitly select the query's fields to avoid an indeterminate loop through query results.
Ok I have managed to get it to work without using get_result()
This is how I did it with alot of help from Parfait and Example of how to use bind_result vs get_result
function saved_rules($user){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT R.rule_id, R.rule_title
FROM Savedrules S
LEFT JOIN Rule R
ON S.saved_rule_id = R.rule_id
WHERE S.saved_user_id = ?");
$stmt->bind_param("i", $user);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $rule_title);
while ($stmt->fetch()) {
$result[] = Array("rule_id"=>$id,"rule_title"=>$rule_title);
}
$stmt->free_result();
$stmt->close();
return $result;
}
Its not exactly the same output as using a mysql_fetch_array() so where it is used I have to change the loop to:
foreach($saved_rules AS $row){}
from
while ($row = mysql_fetch_array($saved_rules){}

How to fetch data from database using prepare statement in php?

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

MySQLi Prepared Statement Query Results in an Array

Trying to transition over my old mysql queries to mysqli prepared statements. I've got everything figured out except for one thing. How can I get the query results stored as an array? I used to do this like this:
$sql = "SELECT * FROM Users";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result) {
// do stuff
}
Now I have the following code. In this case, my array is a single record, so I don't need to iterate over it, but I want to hold it as an array so that I can refer to its field names. Also, I will have other queries that will return multiple records, so I'll need to iterat then.
$sql = "SELECT * FROM Users
WHERE (LOWER(first_name)=LOWER(?) && LOWER(last_name)=LOWER(?))";
$stmt = mysqli_stmt_init($link);
$this_user;
if (mysqli_stmt_prepare($stmt, $sql)) {
/* Bind the input parameters to the query */
mysqli_stmt_bind_param($stmt, 'ss', $first_name, $last_name);
/* execute query, store results in an array */
mysqli_stmt_execute($stmt);
$result = mysqli_fetch_array($stmt);
if (mysqli_num_rows($result) == 0) {
mysqli_stmt_close($stmt);
mysqli_close($link);
$tag_result = "failure";
$tag_message = "No matching user found";
echo encodeJSONObj($tag_result, $tag_message);
die();
}
if (mysqli_num_rows($result) > 1) {
mysqli_close($link);
$tag_result = "failure";
$tag_message = "Multiple records found for this user.";
echo encodeJSONObj($tag_result, $tag_message);
die();
}
$this_user = mysqli_fetch_array($result);
/* close statement */
mysqli_stmt_close($stmt);
}
$id = $this_user['id'];
$first_name = $this_user['first_name'];
$last_name = $this_user['last_name'];
// and so on...
Can somebody tell me what I am doing wrong? Thanks!
EDIT: With big thanks to Phil, I've modified my code. However, I still seem to be returning 0 rows even though my input parameters should return exactly 1 row. Here is what I have:
$sql = "SELECT id, first_name, last_name, group_id, email, cell
FROM Users
WHERE (first_name=? && last_name=?)";
$stmt = mysqli_stmt_init($link);
if (mysqli_stmt_prepare($stmt, $sql)) {
/* Bind the input parameters to the query */
mysqli_stmt_bind_param($stmt, 'ss', $first_name, $last_name);
/* execute query, bind result, and fetch value */
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $first_name, $last_name, $group_id, $email, $cell);
mysqli_stmt_fetch($stmt);
if (mysqli_stmt_num_rows($stmt) == 0) {
mysqli_stmt_close($stmt);
mysqli_close($link);
echo "No results returned";
die();
}
...
}
This always outputs No results returned when it should find 1 row and skip right past that block. I've been staring at this for a long time, but I just can't see what I am doing wrong.
Your script contains numerous errors (as mentioned in comments above). Here's a simple step-by-step...
Prepare a statement and bind parameters
$stmt = $link->prepare($sql);
if (!$stmt) {
throw new Exception($link->error, $link->errno);
}
// you can error check this too but it rarely goes wrong
$stmt->bind_param('ss', $first_name, $last_name);
Execute the statement and store the result
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
$stmt->store_result();
Do your number of row checks against $stmt->num_rows...
if ($stmt->num_rows == 0) {
// ...
}
if ($stmt->num_rows > 1) {
// ...
}
Bind and fetch the result
// This relies on the SELECT column ordering.
// You should probably change your SELECT statement to
// SELECT id, first_name, last_name FROM Users...
$stmt->bind_result($id, $first_name, $last_name);
$stmt->fetch();
$stmt->close();
$link->close();
If you want to fetch the single result row as an associative array, try this instead
$result = $stmt->get_result(); // note - this requires the mysqlnd driver
$this_user = $result->fetch_array(MYSQLI_ASSOC);
$result->free();
$stmt->close();
$link->close();

PHP PDO how do i include fetch assoc and numrows

trying to convert all my old mysql_* operations into new and, from what i've heard, improved PDO, but this query wont seem to run successfully, I am trying to select all from the table PEOPLE where the username = $username (which has previously been declared $username = $_SESSION['username'];)
$query = "SELECT * FROM people WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
if ($num_rows == 1) {
// ...
}
THE WORKING CODE IS:
$query = "SELECT * FROM people
WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
$user = $stmt->fetchObject();
if ($user) {
//do something
}
$stmt->fetchColumn does not fetch the number of rows; in this case it will fetch the first column from the first row of the result set. Since that will not be equal to 1 generally your test will fail.
In this case there is also no real need to count the number of returned rows because you are expecting either one or zero (if the username does not exist). So you can simply do:
$stmt->execute();
$user = $stmt->fetchObject();
if (!$user) {
// not found
}
else {
echo "User $user->username found!";
}
The if(!$user) test works because if there is no row to fetch $user will be false (see the documentation for fetchObject).
$query = "SELECT * FROM people WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->execute();
while ($row = $stmt->fetchObject()) {
// do stuff
}
Use PDOStatement::rowCount as the num_rows and PDOStatement::fetch(PDO::FETCH_ASSOC) as fetch_assoc equivalent.
You want
if ($stmt->num_rows == 1) {
instead.

Categories