When the search matches all displays perfectly. But when there is no match the no result message does not display. Please any insight on this one. Thanks upfront
$result = "SELECT T1.ID, T2.Image1, T1.unoone, T1.unotwo, T1.unothree,
T1.unofour
FROM T1 LEFT JOIN T2 ON (T1.ID=T2.Image1)
WHERE T1.ID=T2.Image1 AND T1.unoone LIKE '%".$uno_one."%'
AND T1.unotwo LIKE '%".$uno_two."%'
AND T1.unothree LIKE '%".$uno_three."%'
AND T1.unofour LIKE '%".$uno_four."%' ";
$stmt = mysqli_stmt_init($con);
$query = mysqli_stmt_prepare($stmt, $result);
if(!$query) {
die("no result");
} else {
/* execute statement */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $id, $img[0], $uno_one, $uno_two,
$uno_three, $uno_four);
/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
echo $img[0];
echo $uno_one;
echo $uno_two;
echo $uno_three;
echo $uno_four;
}
/* close statement */
mysqli_stmt_close($stmt);
}
As Madan Sapkota said : "if(!$query) { only check if any error exists".
You need to use a function for counting results, like mysqli_stmt_num_rows():
if(mysqli_stmt_num_rows ( $stmt ) == 0 ){ echo "there is no result";}
// The while loop after won't be run when no result are found, no need to put an else here.
while (mysqli_stmt_fetch($stmt)) {
...
}
Related
I have this code in PHP where I'm trying to make a JSON based on the result of a prepared statement. The problem is that it is returning a completely white page, nothing appears.
$con = mysqli_connect(HOST,USER,PASS,DB);
$batch_sql = "select * from batchrecord";
$batch_res = mysqli_query($con,$batch_sql);
$row = mysqli_fetch_array($batch_res);
$batch_num = $row[0];
$start = $batch_num * 100;
$end = $start + 99;
if ($stmt = mysqli_prepare($con, "select tweetid, body from tweet where id >=
? and id <= ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ii", $start, $end);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $tweetid, $body);
$result = array();
/* fetch value */
while(mysqli_stmt_fetch($stmt)){
array_push($result,
array('Id'=>$tweetid,
'Body'=>$body,
));
}
/* close statement */
mysqli_stmt_close($stmt);
echo json_encode(array("result"=>$result), JSON_UNESCAPED_UNICODE);
}
else{
echo "Statement Prepare Error";
}
mysqli_close($con);
I already made the content of $tweetid and $body be printed inside the while statement as test and it works fine, meaning that the problem is not the query, but something with the array. What am I missing?
Thanks!
Try like this
$result = array();
while(mysqli_stmt_fetch($stmt)){
$result[] = array('Id'=>$tweetid,'Body'=>$body);
}
Demo :https://3v4l.org/XZOu5
I found the problem after some debugging. The problem was in the json_enconde function, which was silently failing because of JSON_ERROR_UTF8 type of error. I had some problems of special characters from my native language before I had success with just JSON_UNESCAPED_UNICODE before, but this time I added mysqli_set_charset($con, "utf8"); to the top of the code and it is now working. For the sake of completeness, the language is Brazilian Portuguese. The complete code is as follows.
$con = mysqli_connect(HOST,USER,PASS,DB);
mysqli_set_charset($con, "utf8");
$batch_sql = "select * from batchrecord";
$batch_res = mysqli_query($con,$batch_sql);
$row = mysqli_fetch_array($batch_res);
$batch_num = $row[0];
$start = $batch_num * 100;
$end = $start + 99;
if ($stmt = mysqli_prepare($con, "select tweetid, body from tweet where id >=
? and id <= ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ii", $start, $end);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $tweetid, $body);
$result = array();
/* fetch value */
while(mysqli_stmt_fetch($stmt)){
$result[] = array('Id'=>$tweetid,'Body'=>$body);
}
/* close statement */
mysqli_stmt_close($stmt);
echo json_encode(array("result"=>$result), JSON_UNESCAPED_UNICODE);
}
else{
echo "Statement Prepare Error";
}
mysqli_close($con);
Thanks for Barclick Flores Velasquez for the help. I'm new in php and I didn't know there was print_r for debugging, it helped a lot finding the solution.
Using http://php.net/manual/en/mysqli-stmt.bind-result.php as a reference, I created:
$conn = new mysqli($host, $user, $password, $database) or die("Error " . mysqli_error($link));
$userID = json_decode(file_get_contents('php://input'), true)["userID"];
$sql = "SELECT name
FROM users
WHERE id = ?";
$stmt = mysqli_prepare($conn, $sql);
if ($stmt) {
mysqli_stmt_bind_param($stmt, "i", $userID);
if (mysqli_stmt_execute($stmt)) {
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) > 0) {
mysqli_stmt_bind_result($stmt, $name);
while (mysqli_stmt_fetch($stmt)) {
if ($name != "") {
echo '{"name": ' . $name . '}';
} else {
echo '{"name": "Anonymous" }';
}
}
}
}
}
The way this is now, it works in getting the user's name.
However, I'm reluctant to use a while loop when I know my query is only returning one row, so I looked for ways to get the value without using a loop but couldn't find any.
I tried removing the while loop just to see what would happen, and it failed to get the user's name. Is there a way I can get the result of my query using mysqli_stmt_bind_result without using a loop? If not, is there something else I can use to do what I want?
Yes, when you're only expecting one row, and know that it will only return that one, to be returned you don't need to loop over anything - it would be redundant.
You can remove the while-loop, but you'd still need the argument, mysqli_stmt_fetch($stmt) to actually fetch the results.
if ($stmt = mysqli_prepare($mysqli, $sql)) {
mysqli_stmt_bind_param($stmt, "i", $userID);
if (mysqli_stmt_execute($stmt)) {
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) > 0) {
mysqli_stmt_bind_result($stmt, $name);
mysqli_stmt_fetch($stmt);
if (!empty($name)) {
echo '{"name": ' . $name . '}';
} else {
echo '{"name": "Anonymous" }';
}
} else {
// No results!
echo "No results";
}
}
}
I'm trying to figure out why a mysqli parepared statement is not working. I can say the page have something like 2 sections, the first one needs $_GET to be empty and the last one needs $_GET['id'] and other to be set (isset). Both "sections" have the same query but in the last section there's a different query first.
Everyting is working fine until the repeated query in the last "section", where nothing is printed.
I have something like this:
if (login_check($mysqli) == true) {
if(empty($_GET)) { //first section
if ($stmt = $mysqli->prepare("SELECT friends.*, members.*, account_type.* FROM friends INNER JOIN members ON members.id = friends.friendID
INNER JOIN account_type ON account_type.name = members.acc_type
WHERE friends.userID = ? AND members.acc_type = ?")) {
$stmt->bind_param('is', $_SESSION['user_id'], $_SESSION['acc_type']);
$stmt->execute();
} else echo $mysqli->error;
$result = $stmt->get_result();
// php/mysqli stuff working as expected ($row[] printing db data)
// no need to close
}
if(isset($_GET['id'], $_SESSION['user_id'])) { // last section
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT COUNT(*) rowCount FROM friends WHERE friendID = ? AND userID = ?")) {
$stmt->bind_param('ii', $_GET['id'], $_SESSION['user_id']);
$stmt->execute();
/* bind variables to prepared statement */
$stmt->bind_result($rowCount);
/* fetch values */
if($stmt->fetch()) {
if ($rowCount > 0) { // This check is working fine, I tested.
$stmt->close(); // close here so no "non-object" error
$stmt = $mysqli->prepare("SELECT friends.*, members.*, account_type.* FROM friends INNER JOIN members ON members.id = friends.friendID
INNER JOIN account_type ON account_type.name = members.acc_type
WHERE friends.friendID = ? AND members.acc_type = ?");
$stmt->bind_param('is', $_GET['id'], $_SESSION['acc_type']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_array();
// Here I have some $row['columns'] and nothing is printed.
} else{
echo $_SESSION['username'], ', you are not allowed to be here.';
}
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
}
} else {
echo 'Please, log in.';
}
The first query is working fine, the other is a copy/paste.
I don't see where the problem is :(
Thanks!
Edit: sorry the second query should be "WHERE friends.friendID".
for ($i = 1; $i < 13; $i++) {
$month = $row['month' . $i];
if($row[$month] == 1) {
$paid[] = 'Paid';
} else {
$paid[] = 'Not Paid';
}
$bonus = $row['bonus'];
}
The problem is members.monthx and friends.monthx have the same name, but they are not meant to have the same values so I don't know from what table is getting $row['month' . $i]. The value should be taken from friends.monthx. How do I specify that?
I should really know this by now, but I just can't figure it out anyway. Really weird because I thought I knew it but I just can't get it to work anyway. Well I have this code:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if(isset($_POST['item_id'])){
$item_number = $_POST['item_id'];
require('../includes/db_connect.php');
/* Register a prepared statement */
if ($stmt = $mysqli->prepare('SELECT rotation FROM house_room1 WHERE ref_id = ?')) {
/* Bind parametres */
$stmt->bind_param('i', $item_number);
/* Execute the query */
$stmt->execute();
$stmt->bind_result($rotation);
while ($stmt->fetch()) { }
/* Close statement */
$stmt->close();
} else {
/* Something went wrong */
echo 'Something went terribly wrong' . $mysqli->error;
}
/* Register a prepared statement */
if ($stmt = $mysqli->prepare('UPDATE house_room1 SET rotation = ? WHERE ref_id = ?')) {
/* Bind parametres */
$stmt->bind_param('ii', $i, $item_number);
$i = ($rotation + 1) % 5);
/* Execute the query */
$stmt->execute();
/* Close statement */
$stmt->close();
} else {
/* Something went wrong */
echo 'Something went terribly wrong' . $mysqli->error;
}
}
}
As you can see, I have this variable rotation which I get out from the database in the first SELECT statement. I need this value in the next query, UPDATE but the rotation variable is local I guess? So I can't reach it in the next query, how would I do this most effeciently? Thanks in advance.
You can declare $rotation as $rotation=null; after require statement. This way it will be available on the second query.
Here is my code:
$result_username = mysqli_query($dbconnection, Data::checkForUsername($username));
It then goes here:
public static function checkForUsername($username) {
global $database;
$query = "
SELECT COUNT(*)
FROM users
WHERE username='{$username}';";
$result = $database -> query($query);
return $result;
}
Then $result does this:
if (mysqli_result($result_username, 0) > 0) {
However, it then gives me back a Resource_Id?? I can not figure out why?
I simply want to check if the username exists in at least 1 row.
You need to fetch your data after you execute your query
$row = $result->fetch_array(MYSQLI_NUM);
return $row[0];
UPDATE: Now, using prepared statement your function can look like this:
public static function checkForUsername($username) {
global $database;
$result = 0;
$query = "SELECT COUNT(*) FROM users WHERE username=?";
/* create a prepared statement */
if ($stmt = $database->prepare($query)) {
/* bind parameters for markers */
$stmt->bind_param("s", $username);
/* execute query */
$stmt->execute();
/* bind result variable */
$stmt->bind_result($result);
/* fetch value */
$stmt->fetch();
/* close statement */
$stmt->close();
}
return $result;
}
You can try
return $result->num_rows
Then
if (checkForUsername('Redeyes') != 0) {
}