PHP MySQL queries return no results - php

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>";
?>

Related

php stmt similar products display

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);
?>

PHP mysqli not woking [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
So I'm new to mysqli. All of the examples I find online seem to be the old (procedural) way of doing things. Can someone tell me why my code isn't working below? My db is 'templatedb'. My Table is 'template'. I have one entry in my table, but I'm receiving no output with my echo. I'm not getting any errors with my code.
<div id="templateSelector">
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "templatedb";
//connect
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$database = mysqli_connect($hostname, $username, $password, $db);
if(!$database){
die("Could not connect to the database");
}
if ($database->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
} else {
$sql = "SELECT * FROM template";
if (!$result = $database->query($sql)) {
die('There was an error running the query [' . $db->error . ']');
} else {
echo "<label>Select Template</label>";
echo "<select name='templates'>";
while ($row = $result->fetch_assoc()) {
echo "hello";
echo $row['template_name'];
// echo "<option value='" . $row['template'] . "'>" . $row['template'] . "</option>";
}
echo "</select>";
}
}
?>
Try doing the following, worked for me
<div id="templateSelector">
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "templatedb";
$mysqli = mysqli_connect($hostname, $username, $password, $db);
if($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
} else {
$sql = "SELECT * FROM template";
$result = mysqli_query($mysqli, $sql);
if(!$result = $mysqli->query($sql)) {
die('There was an error running the query [' . $db->error . ']');
} else {
echo "<label>Select Template</label>\n";
echo "<select name='templates'>\n";
while($row = $result->fetch_assoc()) {
echo "<option>id = " . $row['id'] . "</option>\n";
}
echo "</select>";
}
}
?>
</div>
Make sure your DATABASE is called templatedb and the table it is in is called template and there is a row called id. I know that sounds trivial, but spelling mistakes will break your code.

i have created this table from database.Now if anyone updates the value in table how can it be reflected back in database?

I am making a simple page to test a database connection. When I tried accessing it from my browser, it says:
Server error
The website encountered an error while retrieving http://localhost:8888/blah/blah/test.php. It may be down for maintenance or configured incorrectly.
Here are some suggestions:
Reload this webpage later. HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.
All I am doing is connecting to a database and displaying the tables. Here is what I have so far as the PHP code:
<?php
// Get Variables
$dbname = $_GET["dbname"];
$dbusername = $_GET["dbusername"];
$dbpass = $_GET["dbpass"];
$dbhost = $_GET["dbhost"];
$connection = mysql_connect("$dbhost","$dbusername","$dbpass");
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
else
{
echo "Connected";
$dbcheck = mysql_select_db("$dbname");
if (!$dbcheck) {
echo mysql_error();
}else{
echo "<p>Successfully connected to the database '" . $database . "'</p>\n";
// Check tables
$sql = "SHOW TABLES FROM `$database`";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
echo "<p>Available tables:</p>\n";
echo "<pre>\n";
while ($row = mysql_fetch_row($result)) {
echo "{$row[0]}\n";
}
echo "</pre>\n";
} else {
echo "<p>The database '" . $database . "' contains no tables.</p>\n";
echo mysql_error();
}
}
// some code
mysql_close($con);
?>
My error in the WAMP Apache logs is:
[03-Feb-2013 22:47:37 UTC] PHP Parse error: syntax error, unexpected end of file in /Applications/MAMP/htdocs/coursemanager/default/verify1.php on line 52
What would a unexpected end of file be?
It means you forgot to close the last }
<?php
// Get Variables
$dbname = $_GET["dbname"];
$dbusername = $_GET["dbusername"];
$dbpass = $_GET["dbpass"];
$dbhost = $_GET["dbhost"];
$connection = mysql_connect("$dbhost","$dbusername","$dbpass");
if (!$connection) {
die('Could not connect: ' . mysql_error());
} else {
echo "Connected";
$dbcheck = mysql_select_db("$dbname");
if (!$dbcheck) {
echo mysql_error();
} else {
echo "<p>Successfully connected to the database '" . $database . "'</p>\n";
// Check tables
$sql = "SHOW TABLES FROM `$database`";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
echo "<p>Available tables:</p>\n";
echo "<pre>\n";
while ($row = mysql_fetch_row($result)) {
echo "{$row[0]}\n";
}
echo "</pre>\n";
} else {
echo "<p>The database '" . $database . "' contains no tables.</p>\n";
echo mysql_error();
}
}
// some code
mysql_close($con);
}

Give argument php function to show database results in another file

I have this php code to connect database it works fine.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cv";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_set_charset($conn,"utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM services";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["service_name"]. " " . $row["service_desc"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
My question is: how to create function getServices() and give argument to show this results in another php file using foreach or while, like this:
<?php foreach ($results as $key=>$result) : ?>
<?php echo $result['service_name']; ?>
<?php endforeach; ?>
Okay. So you have to do the following things:
db.php :
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cv";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_set_charset($conn,"utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function yourFunctionName() {
$sql = "SELECT * FROM services";
$result = $conn->query($sql);
return $result;
}
$conn->close();
otherfile.php :
<?php
include 'db.php';
$data = yourFunctionName();
if ($data->num_rows > 0) {
// output data of each row
while($row = $data->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["service_name"]. " " . $row["service_desc"]. "<br>";
}
} else {
echo "0 results";
}
?>
Hope this works, haven't tested yet.

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

Categories