Simple search function return always 0 results - php

I have this php code
if(isset($_POST['submit'])){
$likeString = '%' . $_POST['search'] . '%';
$query = $conn->prepare("SELECT * FROM images WHERE image_caption LIKE ?");
$query->bind_param('s', $likeString);
$query->execute();
var_dump($likeString);
if (!$query) {
printf("Query failed: %s\n", $mysqli->error);
exit;
}
if($res->num_rows > 0) {
while ($row = $res->fetch_assoc()) {
echo "<br>Title: " . $row['image_caption'];
}
} else {
echo " <br> 0 results";
}
}
var_dump($likeString) shows the word which I've posted via search form correctly. Also I've tried in phpmyadmin directly to run this query
SELECT *
FROM images
WHERE image_caption LIKE "%Volvo%"
And I've received 1 result which is correct. On page I see 0 results. Tried to play with fetch:
$res->fetch_assoc()
$res->fetchAll()
$res->fetch()
none of them show any result. I'm sure is something very silly and simple mistake but can't see it. Please help on this.
I don't have Call to a member function bind_param() on a non-object It was my mistake while I've made proposed changes from one of the answer. Problem still remains - 0 Results
UPDATE: Current code
$likeString = "%{$_POST['search']}%";
$query = $conn->prepare("SELECT * FROM images WHERE image_caption LIKE ? ");
$query->bind_param('s', $likeString);
$query->execute();
if($query->num_rows > 0) {
while ($row = $query->fetch()) {
echo "<br>Title: " . $row['image_caption'];
}
} else {
echo " <br> 0 results";
}
}
UPDATE 2: DB connection checked-> result is Connected successfully
$servername = "localhost";
$username = "mydbUsername"; // it's changed for the question
$password = "myPass"; // it's changed for the question
$dbname = "myDbName"; // it's changed for the question
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

You are using $res while it is not defined... You must use $query instead.
Next time turn on error reporting to see such silly bugs

try this : (update your code)
$likeString= "%{$_POST['search']}%";
$stmt = $db->prepare("SELECT * FROM images WHERE image_caption LIKE ?");
$stmt->bind_param('s', $likeString);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM))
{
foreach ($row as $r)
{
echo "<br>Title: " . $r['image_caption'];
}
print "\n";
}
OR
<?php
$conn = new mysqli("localhost","mydbUsername","myPass","myDbName");
/* check connection */
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$query = "SELECT * FROM images WHERE image_caption LIKE %".$_POST['search']."%";
if ($result = $conn->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo "<br> Title: ". $row["image_caption"]);
}print "\n";
/* free result set */
$result->free();
}
/* close connection */
$conn->close();
?>

Related

Why does my PDO $stmt->bind_result() function call hang after executing a SELECT query?

I have a MySQL database with table "Test" that has one column "TestData". There are three records with the following values for TestData: "This is value 1", "Here is another string", and
"Third just for luck".
I wrote the following PHP code to retrieve the records.
<?php
try {
$hostname = "redacted";
$username = "redacted";
$password = "redacted";
$database = "redacted";
$conn = new PDO("mysql: host=$hostname; dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT TestData FROM Test";
$stmt = $conn->prepare($sql);
$stmt->execute();
}
catch(PDOException $e)
{
$finalResult = $finalResult . "," . $e->getMessage();
}
echo "you are here (" . $stmt->rowCount() . ")<br>";
if ($stmt->rowCount() > 0) {
echo "found (" . $stmt->rowCount() . ")<br>";
$stmt->bind_result($td);
echo "bind successful<br>";
while ($stmt->fetch()) {
echo "testdata (" . $td . ")<br>";
}
} else {
echo "nothing found<br>";
}
?>
The result I receive is
you are here (3)
found (3)
The PHP script never gets to the "echo 'bind successful'" statement. The "$stmt->bind_result($td);" statement hangs.
The query appears to work, given that rowCount = 3. I've used essentially the same structure to perform INSERTS that work properly.
What's wrong with what I'm doing? Thanks.
I changed my code to the following and it works.
<?php
$hostname = "redacted";
$username = "redacted";
$password = "redacted";
$database = "redacted";
$conn = new mysqli($hostname, $username, $password, $database);
if ($conn->connect_error) {
fwrite(STDERR, "Connection failed: " . $conn->connect_error . "\n");
exit(1);
}
$sql = "SELECT TestData FROM Test WHERE ?";
$stmt = $conn->stmt_init();
if(!$stmt->prepare($sql)) {
print "Failed to prepare statement\n";
} else {
$stmt->bind_param("s", $condition);
}
$condition = "1 = 1";
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
foreach ($row as $r) {
echo "testdata(" . $r . ")<br>";
}
}
?>
No more mixing PDO and MySQLi for me. Thanks for the help. Sorry for the inconvenience.
If you are just trying to get the items from the database using php pdo you need to store the results.
$results = $stmt->fetch(); //will get one row
$results = $stmt->fetchAll(); //will take all results and store in an array
hope this helps.

Get rows from database

I have a connection where i want to get some data from my database.
I have inserted some data but now i want to retreive it but i get NULL.
I have no idea why.
<?php
require "connect.php";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM tbltemperature ORDER BY time DESC LIMIT 1";
$result = $conn->query($sql);
var_dump($results);
$t = 0;
while($row = $result->fetch_assoc()) {
$weather[] = array(
$row["time"],
$row["inside_temperature"]
);
echo $row["time"];
echo $row["inside_temperature"];
}
$conn->close();
?>
check var_dump($results); , it looks like it should be var_dump($result);
otherwise you should check $result->num_rows() first to know if there is any row available.
Firstly you have to check your query in phpmyadmin query is working or not. If working you should try to var_dump($result); and after
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> time: ". $row["time"]. " - inside_temperature: ". $row["inside_temperature"]."<br>";
}
} else {
echo "0 results";
}

I can't get any data output from the database, i only get "0 results" as the else statement, what's the case?

I'm having some troubles with fetching some database information with my php code.
All I'm getting is this message: "Connected successfully0 results".
Here's my code guys, thanks for the help in advance.
<?php
$servername = "example";
$username = "example1";
$password = "example2";
$row = array();
$conn = new mysqli($servername,$username,$password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "Select Distinct subject from mobile_math_science_toc";
$result = mysqli_query($conn, $sql);
if ($result = $conn->query($sql)) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Subject " ,$row["subject"];
}
} else {
echo "0 results ";
}
mysqli_close($conn);
?>
You should add dbname while creating your connection to database. You can use mysqli_num_rows function to count no. of rows.
<?php
$servername = "example";
$username = "example1";
$password = "example2";
$dbname = "your_db_name"; // Specify your db-name here.
$conn = new mysqli($servername,$username,$password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "Select Distinct subject from mobile_math_science_toc";
$result = mysqli_query($conn, $sql);
// Checking if there are some records available.
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Subject " ,$row["subject"];
}
} else {
echo "0 results ";
}
mysqli_close($conn);
?>
Change
$conn = new mysqli($servername,$username,$password);
To
$conn = new mysqli($servername,$username,$password, "<your database name>");
And
$result = mysqli_query($conn, $sql);
if ($result = $conn->query($sql)) {
}
To
$result = $conn->query($sql);
if ($result) {
}
Try
if (mysqli_num_rows($result) > 0) {
While checking you got the data or not

first php query error

I'm trying to write my first PHP query and I'm getting the following
error:
Notice: Trying to get property of non-object in
D:\Home\web\username\helloworld.php on line 36.
What am I doing wrong?
Code:
<?php
ini_set('display_errors', 1);
error_reporting(~0);
$servername = "myserver.com";
$username = "myusername";
$password = "mypassword";
$dbname = "mydbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM books";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Okay, so your code looks like this:
$sql = "SELECT * FROM books";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. "<br>";
}
} else {
echo "0 results";
}
The Problem lies in $result->num_rows > 0
Apparently you have an Error in your query so your $result is a boolean instead of an Object, so the property num_rows doesnt exist. A better solution would be:
if($result !==false){
//handle your result here
}else{
echo "An error appeared: ".$conn->error;
}
Your syntax and logic is correct but the query is not executing successfully. Try putting an if condition before the if ($result->num_rows > 0) condition to check that.
Also, I was able to reproduce the error by misspelling the name of the table. So, are you sure that the table books exists in your database? Correcting that will solve it.
Your query has a problem with it. Have you got a table called books? Did you spell it wrong?
Your code: if ($result->num_rows > 0) { is causing the problem because the query didn't return a success. So how can it get the num_rows?
You want to check for a MySql error before you run that if statement so try this final code and find out what the error is:
<?php
ini_set('display_errors', 1);
error_reporting(~0);
$servername = "myserver.com";
$username = "myusername";
$password = "mypassword";
$dbname = "mydbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM books";
$result = $conn->query($sql);
if($result !== false){
//query was a success!
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. "<br>";
}
} else {
echo "0 results";
}
}else{
//your query had an error so lets display it:
echo "Query Error: ".$conn->error;
}
$conn->close();
?>
What is the Error you now get printed out?

PHP SELECT * FROM not working

I am trying to query data from a table using the following script:
//connect file
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//connect file included above - ECHO tested and it is connected as $conn
$sql = "SELECT * FROM userInfo";
$results = $conn->query($sql);
if (!$results) {
printf("Errormessage: %s\n", $conn->error);
exit;
} else {
echo $row['username'];
}
UPDATE --
It now no longer tries to throw an error and seems to go to the else section; however, no echo - and the spelling is correct this time and the column is filled.
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["username"];
}
} else {
echo "0 results";
}
This now returns results. Thank you #Fred -ii- especially for your help on this.
Also thanks #jjczopek for the error checking advice!

Categories