PHP not returning mysql results - php

I am brand new to PHP, or database programming in general. For a project I have to query a bookstore database for book info (a very small database) and display it on the following page. Below is the code for my bookstore search page:
<?php
$con = mysqli_connect("localhost", "root", "root") or die("Error connecting to database: ".mysqli_error());
mysqli_select_db($con, "bookstore") or die(mysqli_error());
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Book Store</title>
</head>
<body>
<td><h1>Book Search</h1> </td>
<table width="100%" border="0">
<tr>
<form method="post" action="search.php?go" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search By Title">
</form>
<form method="post" action="search.php?go" id="searchform">
<input type="text" name="category">
<input type="submit" name="submit" value="Search By Category">
</form>
</tr>
</table>
</body>
</html>
And the following is a simple search.php code that query's my database and returns results. However I am unable to see any results. The only thing that shows up is "Book Title Search Results" with nothing below. Which obviously means my problem is in my while loop.
<?php
$con = mysqli_connect("localhost", "root", "root") or die("Error connecting to database: ".mysqli_error());
mysqli_select_db($con, "bookstore") or die(mysqli_error());
?>
<!DOCTYPE html>
<html>
<head>
<title>Search Results</title>
<meta http-equic="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
if (isset($_POST['name'])){
$query = $_POST['name'];
$sql = mysqli_query($con, "SELECT * FROM books
WHERE (`title` LIKE '%".$query."%')") or die(mysqli_error($con));
if (mysqli_num_rows($sql) > 0) {
echo "</br> Book Title Search Results </br>";
while ($row = mysqli_fetch_array($sql, MYSQL_ASSOC)) {
echo "</br>Title: " .$row['title']. ", Author: " .$row['author'].", Year: " .$row['year'] . ", Price: $" .$row['price'] ."</br>";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['cover'] ).'"/>';
}
}else{ // if there is no matching rows do following
echo "No results";
}
}
?>
</body>
</html>
I have 6 columns in my database: title, author, year, price, category, image (BLOB FILE), and I have checked naming in my query functions but cannot figure anything out. Can anyone push me in the right direction or show me what I'm doing wrong? I'm using MAMP web server.

There is a typo in your code. Use MYSQLI_ASSOC instead of MYSQL_ASSOC. The rest of the code is correct.

try
$con = mysqli_connect("localhost", "root", "root", "bookstore") or die("Error connecting to database: ".mysqli_error());

In your query, remove the braces after the where:
$sql = mysqli_query($con, "SELECT * FROM books WHERE title LIKE '%$query%'") or die(mysqli_error($con));
Then fetch the results with:
while ($row = mysqli_fetch_assoc($sql)) {
//code
}

Related

PHP Search is not working

I don't understand what's the problem with the code. It is supposed to work. There is data in table but the search is still not producing any results. The Search bar remaining still and no changes before or, after entering any data in the search bar.
Here is the code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Search Example</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" placeholder="Search" />
<input type="submit" value="submit" />
</form>
<?php
$con = mysqli_connect("localhost","root","") or die("Could not connect");
mysqli_select_db($con ,"project") or die(mysqli_error());
if(isset($_POST['search']))
{
$search =$_POST['search']; // searchq contains characters which is typed
in the search
$search = preg_replace("#[^0-9a-z]#i","",$search); //filtering the
conditions */
$query = mysqli_query($con, "SELECT * FROM admin WHERE name LIKE
'%$search%'");
//most important condition line for the search
$count = mysqli_num_rows($query); // To count the selected Rows
if($count==0)
{
echo"<h2>"."No Data Found"."</h2>";
}
else
{
while($row = mysqli_fetch_array($query))
{
echo "<tr>".
"<td>".$row['username'] ."</td>".
"<td>".$row['password'] ."</td>".
"</tr>";
}
}
}
?>
</body>
</html>
Database name is project and table name is admin with Id, username and password as columns.
Use like this
$query = mysqli_query($con, "SELECT * FROM `admin` WHERE `username` LIKE
'%{$search}%'");
Do it like this:
$query = mysqli_query($con, "SELECT * FROM admin WHERE name LIKE
'%{$search}%'");
By surrounding variable in {} you can specify that only $title is a variable and the double-quote string will ensure that this variable gets expanded to its value.

mysqli fetch array error Couldn't fetch mysqli

I am trying to input and display the data on same page through mysqli but it shows an error "Couldn't fetch mysqli on line" and not unable to display the records.
<?php
$db=mysqli_connect("localhost","root","","abc") or die("Not connected".mysqli_error());
$database=mysqli_select_db($db,'abc') or die("Database not found".mysqli_error());
if(isset($_POST['submit'])){
$roll=$_POST['roll'];
$name=$_POST['name'];
$ins=mysqli_query($db,"insert into abc1 (roll,name)values('$roll','$name')");
}
mysqli_close($db);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form method="post">
Roll No <input type="text" name="roll" />
Name <input type="text" name="name" />
<input type="submit" name="submit" value="Submit" />
</form>
<table><tr>
<td>Roll No.</td>
<td>Name</td>
</tr>
<?php $query=mysqli_query($db,"select * from abc1");
$result=mysqli_query($db,$query);
$id=0;
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
?>
<tr><td><?php echo $row['roll']; ?></td>
<td><?php echo $row['name']; ?></td>
<?php } ?>
</tr></table>
</body>
</html>
Any help would be appreciated.
Thanks in Advance
You are doing mysqli_query twice.
Try this.
$query = "select * from abc1";
$result = mysqli_query($db, $query);
You are calling mysqli_query function twice:
$query = mysqli_query($db,"select * from abc1");
$result = mysqli_query($db,$query);
Error: Couldn't fetch mysqli on line
Means, you are passing a a resource id in mysqli_fetch_array function instead of Query Statement. so you just need to use this as:
$query = "select * from abc1";
$result = mysqli_query($db,$query);
Side Note:
There is no need to connect db again:
$database=mysqli_select_db($db,'abc')
mysqli_connect() already connected your db.

Display data from sql using php

I have written a very simple PHP to search for a record in a field on MySQL database and return all details for that field.
Unfortunately, every time I enter the number to search for anything, nothing comes back, not even any errors.
My Code below:
<?php
mysql_connect("localhost", "root", "") or die("cant connect to db");
mysql_select_db("db name")or die("cant connect.....");
$output='';
//collect
if(isset($_POST['search'])){
$searchq=$_POST['search'];
$query = mysql_query("SELECT * FROM register WHERE licence LIKE '%$searchq%'") or die("cant search....");
$count = mysql_num_rows($query);
if($count==0){
$output='no results';
} else {
while($row=mysql_fetch_array($query)){
$fdriver=$row['driver'];
$flicence=$row['licence'];
$fofficer=$row['officer'];
$fspeed=$row['speed'];
$ffine=$row['fine'];
$fcategory=$row['category'];
$output.='<div> '.$fdriver.' '.$flicence.' '.$fspeed.' '.$ffine.' '.$fcategory.'</div>';
}
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Search</title>
</head>
<body>
<h3>Search</h3>
<p>You have to enter your number to search</p>
<form method="post" action="search_start.php" >
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
<?php print("$output"); ?>
</body>
</html>
first change the name of your textbox to search
<input type="text" name="search">
second your query should be like this
$query = mysql_query("SELECT * FROM register WHERE licence LIKE '%".$searchq."%'");
You're checking $_POST['search'], so the name of your text element field should be changed to search.
<input type="text" name="search">

Retrieve and display images from MySQL database (with condition)

I'm having a problem on developing my website..
First, I have 2 tables:
1- Products: contains info. about the products & 2- Images: which contains product images.
The idea is that : I want to insert an image or two for a specified product and display that image for that product only..
In the mean time, I can insert images into the database and I can also display them.. but my issue is that when I try to do display.. the code retrieves all images from Images table..
so my question: how can I display image/s for only one product .. not all images in that table? I'm confused in how to make this condition.. need ur help guys :?
Here's my code:
File1: imageUpload.php
<?php
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
mysql_connect("localhost", "root", "");
mysql_select_db ("myDB");
$imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "INSERT INTO Images(imageType ,imageData, product_id)
VALUES('{$imageProperties['mime']}', '{$imgData}','{$_POST['memids']}')";
$current_id = mysql_query($sql) or die("<b>Error:</b> Problem on Image Insert<br/>" .
mysql_error());
if(isset($current_id)) {
header("Location: listImages.php");
}
}
}
?>
<HTML>
<HEAD>
<TITLE>Upload Image</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<form name="frmImage" enctype="multipart/form-data" action="" method="post"
class="frmImageUpload">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" required/>
<input type="submit" name="submit" value="Submit" class="btnSubmit" /><br><br>
</form>
</div>
</BODY>
</HTML>
File2: listImages.php
<?ob_start()?>
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("myDB");
$sql = "SELECT imageId FROM Images
ORDER BY imageId DESC";
$result = mysql_query($sql);
?>
<HTML>
<HEAD>
<TITLE>List BLOB Images</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<?php
while($row = mysql_fetch_array($result)) {
?>
<img src="imageView.php?image_id=<?php echo $row["imageId"]; ?> "width="200" /><br/>
<?php
}
mysql_close($conn);
?>
</BODY>
</HTML>
<?ob_flush()?>
File3: imageView.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("myDB") or die(mysql_error());
if(isset($_GET['image_id'])) {
$sql = "SELECT imageType,imageData FROM Images WHERE imageId=" . $_GET['image_id'];
$result = mysql_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["imageData"];
}
mysql_close($conn);
?>

php not passing data to mysql

I have a php page that connects to a mysql database. I know that the connection to the database is good because I have a php code that displays info from the database onto the webpage. When I try to insert new data into the databse, the page refreshes and the data is not inserted. I have checked to insure that the insert into command has the correct values.
<?php
if (isset($_POST['User_Name']))
{
include "connect_to_mysql.php";
$name = mysql_real_escape_string($_POST["Name"]);
$sql = mysql_query("SELECT TestID FROM test WHERE Name='$name' LIMIT 1")or die (mysql_error());
$productMatch = mysql_num_rows($sql);
if ($productMatch > 0)
{
echo 'Sorry you tried to place a duplicate "User Account" into the system, click here';
exit();
}
else
{
$sql = mysql_query("INSERT INTO test (TestID,Name)
VALUES('', '$name')") or die (mysql_error());
$uid = mysql_insert_id();
header("location: index.php");
exit();
}
}
?>
<?php
include "connect_to_mysql.php";
$User_list = "";
$sql = mysql_query("SELECT * FROM test");
$UserCount = mysql_num_rows($sql);
if ($UserCount > 0)
{
while($row = mysql_fetch_array($sql))
{
$id = $row["TestID"];
$name = $row["Name"];
$User_list .= "Users ID: $id - <strong>$name</strong> <br />";
}
}
else
{
$User_list = "You have no users listed in the database.";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div align="center" id="mainWrapper">
<div id="pageContent"><br />
<div align="right" style="margin-right:32px;">+ Add New User</div>
<div align="left" style="margin-left:24px;">
<h2>User list</h2>
<?php echo $User_list; ?>
</div>
<hr />
<a name="UserForm" id="UserForm"></a>
<h3>
↓ Add New User Form ↓
</h3>
<form action="index.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
<table width="90%" border="0" cellspacing="0" cellpadding="6">
<tr>
<td width="20%" align="right">Name</td>
<td width="80%"><label>
<input name="name" type="text" id="name" size="50" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Add This Name Now" />
</label></td>
</tr>
</table>
</form>
<br />
<br />
</div>
</div>
</body>
</html>
I see two problems right away (there may be more). First, PHP array keys are case sensitive. You are accessing $_POST['Name'] but your form input is name. Second, you are testing for $_POST['User_Name'] which doesn't appear to exist anywhere:
// Look for name in the $_POST
if (isset($_POST['name']))
{
include "connect_to_mysql.php";
// name is case-sensitive
$name = mysql_real_escape_string($_POST["name"]);
Later, if your table has an AUTO_INCREMENT id on TestID, you should either omit it or insert NULL in the insert statment:
// Don't include TestID if it is AUTO_INCREMENT. That will happen automatically
$sql = mysql_query("INSERT INTO test (Name)
VALUES('$name')") or die (mysql_error());
I think it will work if you change
if (isset($_POST['User_Name']))
to
if (isset($_POST['Name']))
You check the existence of something which doesn't exists in your form.
Addition:
If TestID is autoincrement, change the below
"INSERT INTO test (TestID,Name) VALUES('', '$name')"
to
"INSERT INTO test (Name) VALUES('$name')"
If you do not get any errors that means you have an error in your MySQL syntax two ways to test it would be to copy the syntax into PHPMyAdmin or whatever your native MySQL command line is and see if you get an output error. Or another thing you can do is to modify all your mysql_query(); functions by adding mysql_query()or die(mysql_error());

Categories