php stmt similar products display - php

I am creating PHP stmt similar products display script this script working but not showing similar products I want to display similar products title
Here is my code
<?php
$id=$row['id'];
if($stmt = $con->prepare("SELECT title
FROM products order by rand() limit 3
")){
$stmt->execute();
}
$result = $stmt->get_result();
if($result->num_rows > 0){
while($row = $result->fetch_array(MYSQLI_ASSOC)){
//results
}}
?>
view.php
<?php
if(isset($_GET['id'])) {
include("config.php");
$id = $_GET['id'];
$sql = "select * from products where id = '$id'";
$result = $con->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
//results
}}}
?>

Ensure that Database credentials were okay.
Try the code below and let me know
1) Query using rand() method( This is what you want)
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = 'your password goes here';
$dbname = 'your database goes here';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
$sql = 'SELECT title FROM products order by rand() limit 3';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Title: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
2.) Query Using where Clause in this case an id(1) to show product title where id of 1 matches it in the database
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = 'your password goes here';
$dbname = 'your database goes here';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
$sql = "SELECT id,title FROM products where id='1'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Title: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Updated Section
First create table below and insert into it
create table products(id int(11) primary key auto_increment,title varchar(30),description varchar(30),image varchar(30),cat_id int(11));
You will insert at least one record
insert into products (id,title,description,image,cat_id) values(1,'product title','product details','product.png',100);
For testing query the products table to get details where id is 1
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'anglejs';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
$sql = "SELECT id,title,description,image,cat_id FROM products where id='1'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Id: " . $row["id"]. "<br>";
echo "Title: " . $row["title"]. "<br>";
echo "description: " . $row["description"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Now since the Id is coming from url
For testing purpose:
You can save the code as view.php like you did
Open your browser and Enter something like
http://localhost/-----yourfolder diretory goes here-----/view.php?id=1
You can see Id of 1 coming from the Url as appended to view.php files. since we have inserted record which has id of 1, the code below will display the
records only for rows where id is = 1 and so on....
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'anglejs';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
$id = $_GET['id'];
//check if id is empty
if($id==''){
echo "Id is empty";
exit;
}
$sql = "SELECT id,title,description,image,cat_id FROM products where id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Id: " . $row["id"]. "<br>";
echo "Title: " . $row["title"]. "<br>";
echo "description: " . $row["description"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>

Related

PHP MySQL queries return no results

My queries to MySQL via PHP are returning no results. First, I have tried connecting and doing a select on a known table and get no results. I then try to get a listing of the tables and again no results. When I look at the database via phpMyAdmin I can see the tables and their contents. Here is my code. Can anyone offer some help as to what I am doing wrong?
<?php
# /* $ php -f db-connect-test.php */
echo"preparing to connect";
$dbname = '#########';
$dbuser = '#########';
$dbpass = '#########';
$dbhost = 'localhost';
$connect = #mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die("Unable to Connect to '$dbhost'");
echo"<html>";
echo"<title>test page</title>";
echo"<body>";
echo"<h2> test page</h2>";
/* check connection */
if ($conn->connect_error) {
die("Connection failed: " . mysqli_connect_error());
}
else{
echo"Successfully Connected <p>";
}
if(mysqli_ping($connection)){
echo "got it<p>";
}
$sql = "SELECT * FROM `announcements`";
$result = mysqli_query($dbname, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo 'date: ' . $row['date'] . '\tTitle: ' . $row['title'] . '\tBody: ' . $row['body'] .'<br />';
}
} else {
echo "0 results<p>";
$sql = "SHOW TABLES";
$result = mysqli_query($dbname, $sql);
if (!$result) {
echo "DB Error, could not list tables<p>";
echo 'MySQL Error: ' . mysqli_error();
}
else{
while ($row = mysqli_fetch_row($result)) {
echo "Table: {$row[0]}<p>";
}
}
}
$conn->close();
echo"</body>";
echo"</html>";
?>
Here is the result I am seeing:
preparing to connect
test page
Successfully Connected
0 results
DB Error, could not list tables
MySQL Error:
end of results
For some reason I am unable to get MySQL to return a error message.
When calling mysqli_query()
mysqli_query($dbname, $sql);
The first parameter is your database link not the name...
mysqli_query($connect, $sql);
Also - don't use # for your connection (or preferably anywhere) as this suppresses errors.
Update:
Also just noticed...
mysqli_ping($connection)
which should be...
mysqli_ping($connect)
You just have to Copy and Paste this code
You don't have to use $dbname
Have to use $connect
<?php
# /* $ php -f db-connect-test.php */
echo"preparing to connect";
$dbname = '#########';
$dbuser = '#########';
$dbpass = '#########';
$dbhost = 'localhost';
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die("Unable to Connect to '$dbhost'");
echo"<html>";
echo"<title>test page</title>";
echo"<body>";
echo"<h2> test page</h2>";
/* check connection */
if ($conn->connect_error) {
die("Connection failed: " . mysqli_connect_error());
}
else{
echo"Successfully Connected <p>";
}
if(mysqli_ping($connection)){
echo "got it<p>";
}
$sql = "SELECT * FROM `announcements`";
$result = mysqli_query($connect, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo 'date: ' . $row['date'] . '\tTitle: ' . $row['title'] . '\tBody: ' . $row['body'] .'<br />';
}
} else {
echo "0 results<p>";
$sql = "SHOW TABLES";
$result = mysqli_query($connect, $sql);
if (!$result) {
echo "DB Error, could not list tables<p>";
echo 'MySQL Error: ' . mysqli_error();
}
else{
while ($row = mysqli_fetch_row($result)) {
echo "Table: {$row[0]}<p>";
}
}
}
$conn->close();
echo"</body>";
echo"</html>";
?>

how to convert the text outputted from a database to links?

Iam class 11th..recently I started learning php and mysqliI have been facing a problem. I am trying to create a database which has a small list of movies.when the page loads, it displays the list of those movies from database..but the problem is, it displays them as a simple text..i Want them to be like links so that whenever it is clicked it displays the info about that particular movie..but i dont want to write anchor tag links for each movie..Is there any other way?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, title FROM movies";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
According to your code.
if ($result->num_rows > 0) {
$htmlLink = '';
while($row = $result->fetch_assoc()) {
$id = $row["id"];
$title = $row["title"];
$htmlLink .= "<a href='movie.php?{$id}'>id: {$id} - Name: {$title}</a><br>";
echo $htmlLink;
}
} else {
echo "0 results";
}
Then on your movie.php page use $_GET[] to get the query string data
Replace:
echo "id: " . $row["id"]. " - Name: " . $row["title"]. "<br>";
With:
$id = $row["id"];
$title = $row["title"];
echo "<a href='/movie/{$id}'>id: {$id} - Name: {$title}</a><br>";

CONCAT function in MySQL using PHP Undefined Variable

I need help on how to do this correctly. I need to execute this command:
SELECT concat(branchname, -->, itemtype, '(, quantity, ')') from monitoring
order by itemtype;
the syntax works in MySQL console. However, im having trouble with implementing it on php. I always get
"Undefined index: branchname"
"Undefined index: itemtype"
"Undefined index: quantity"
using this code:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dex_test";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT concat(branchname,itemtype,quantity) from monitoring order by itemtype";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo " " . $row["branchname"]. " " . $row["itemtype"]. " ".$row["quantity"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
The error says it's in this line
echo " " . $row["branchname"]. " " . $row["itemtype"]. " ".$row["quantity"]. "<br>";
Im confused because I basically ran the same code that worked that lets me see the itemtype in the table:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dex_test";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT itemtype FROM monitoring";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "itemtype: " . $row["itemtype"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
Help anyone?
It seems your query needs update
"SELECT concat(branchname,itemtype,quantity) from monitoring order by itemtype";
It should be
"SELECT branchname,itemtype,quantity from monitoring order by itemtype";
I have posted this answer in reference of how you were calling your fields in while loop
echo " " . $row["branchname"]. " " . $row["itemtype"]. " ".$row["quantity"]. "<br>";
and if you need to show the concat value within one field than it should be something like
$sql = "SELECT concat(branchname,' ',itemtype,' ',quantity) as branch from monitoring order by itemtype";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["branch"]."<br>";
}
} else {
echo "0 results";
}
Just define the alias for the concatenated columns. Use this -
SELECT concat(branchname,itemtype,quantity) as branchname from monitoring order by itemtype
Or if you want them seperately then -
SELECT branchname, itemtype, quantityfrom monitoring order by itemtype

If 0 items in DB table, return error

I am looking for a way to display an error message if there is nothing listed in the table.
I have a photos table.
If this tables is empty, id like to echo something.
else, show the pictures.
inside of that table I have
id, name, url
id = id
name = name of image
url = url of image.
If there are no rows, we have an error.
$query1 = mysql_query("SELECT COUNT(*) FROM photos;");
mysql_fetch_array($query1);
if(empty($query1)) {
echo "nothing";
} else {
echo "good";
}
Try this,
$query = "SELECT * FROM photos";
$result= mysql_query($query);
$length= mysql_num_rows($result);
if($length>0)
{
while($rows = mysql_fetch_array($result))
{
echo $rows['name'];
echo "<img src='$rows[url]' />";
}
}
else
{
echo "Nothing to display";
}
Hope this will work
What about something like...
$sql = "SELECT COUNT(*) AS amountPhotos FROM photos";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row["amountPhotos"] == 0) {
echo "There are no photos in the photo table.";
}
or
$sql = "SELECT * FROM photos LIMIT 1";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "There are no photos in the photo table.";
}
Try this
$query1 = mysql_query("SELECT COUNT(*) FROM photos;");
$result = mysql_fetch_array($query1);
if(empty($result)) {
echo "nothing";
} else {
echo "good";
}
This pretty much sums up the answer for this question: http://www.w3schools.com/php/php_mysql_select.asp
They even provided a sample code:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //<--- here they check if number of rows returned is greater than 0 (so there is data to display)
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results"; //<----- nothing found
}
$conn->close();
?>
Just modify this and you'll be good to go.

Make a hyperlink from SQL and PHP

I have several "providers" with website urls listed in a table. I am wondering how I would link their websites that are listed in the table to make them live urls.
<?php if($Website){
echo "<div class='providerData1'>Website: </div> <div class='providerData1 providerData2'>" . $Website . "</div><br />"; }
?>
Any ideas? Thank you. :)
Base yourself on the following: (details can be found in comments)
<?php
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
if($db->connect_errno > 0){
die('Unable to connect [' . $db->connect_errno . ']');
}
// Use
// $sql = mysqli_query($db, "select * from tablename ");
// Or select particular columns
$sql = mysqli_query($db, "select link,name from tablename LIMIT 1");
// You can remove LIMIT 1 if you want to show them all
echo "Pages (found):";
echo "<hr>";
while ($row = mysqli_fetch_array($sql)){
$name= $row['name'];
$Website = $row['link'];
echo $name;
echo "<br>";
echo "<div class='providerData1'>Website: </div> <div class='providerData1 providerData2'><a href='$Website'>" . $name . "</a></div><br />";
}
echo "<br>";
?>
In place of the entire while loop, you can replace it with:
Sidenote (having a URL for the link column)
echo '<table><tr><th>Name</th><th>Page</th><th>Link</th></tr>';
while ($row = $result->fetch_assoc()){
echo '<tr><td>'.$row["name"].'</td>';
echo '<td>'.$row["link"].'</td>';
echo '<td>Link</td></tr>';
}
echo '</table>';
and display your links neatly in an HTML table.

Categories