Unable to fetch data equal to 0 - php

I have a small database that will show data being updated as 0 and not as 1. When I try to run the following sql query
Database PHP
// Connect To DB
$hostname="localhost";
$database="xxxx";
$username="xxxxx";
$password="xxxxx";
#$conn = mysqli_connect($hostname, $username, $password)
or die("Could not connect to server " . mysql_error());
mysqli_select_db($conn, $database)
or die("Error: Could not connect to the database: " . mysql_error());
/*Check for Connection*/
if(mysqli_connect_errno()){
// Display Error message if fails
echo 'Error, could not connect to the database please try again again.';
exit();
}
$query = 'SELECT * FROM mods ORDER BY id where updated="0"';
$result = mysqli_query($conn, $query);
#$num_results = mysqli_num_rows($result);
I have tried wrapping and not wrapping the 0 in '' and "".
Currently it just loads the HTML table without data. If I remove the where statement, it pulls fine.
HTML PHP
for($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
?>
<tr>
<td style=""><?php print $row['mod_name']; ?></td>
<td style=""><div id"tdcenter" style="width: 44px;white-space:nowrap;overflow: hidden;text-overflow: ellipsis;text-align:center;"><?php print $row['mod_version']; ?></div></td>
<td style=""><?php print $row['time']; ?></td>
</tr>
<?php
// end loop
}
?>

Please try these and check which one works for you:-
As #BigRabbit says :- $query = "SELECT * FROM mods ORDER BY id where updated='0'";
create a variable $update = 0;
and now append it to your query $query = "SELECT * FROM mods ORDER BY id where updated=".$update;
Another attempt is swapping ORDERBY and WHERE clause.

The syntax on your query is wrong try this:
$query = "SELECT * FROM mods ORDER BY id where updated='0'";

Related

PHP MYSQL Table Row Click to Display Details of the Data

I'm trying to display more details of the data when the table row <tr> is clicked. But I have no idea how to implement it. Here's my code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hotel_dir";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT hotel_img, hotel_name, hotel_address, hotel_phone FROM hotel";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td><img src=".$row["hotel_img"].
"></td><td>".$row["hotel_name"].
"<br />".$row["hotel_address"].
"</td><td>".$row["hotel_phone"].
"</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Here's the image.
hotel list
The problem is, I'm trying to pass it to hotel.php showing more details of the hotel when the table row is clicked.
You must have an Id field in your hotel table you can include it and have an anchor tag to link to other page with this id,
actually some thing like this:
For SQL statement:
for SQL statement you select id and the previous fields that you had selected already, as usually id is a unique column in tables you can get detail of one row and show all detail of specied id.
Here in this page your sql statement should change to :
$sql = "SELECT id,hotel_img, hotel_name, hotel_address, hotel_phone FROM hotel";
and in the detail.php page your SQL statement must be something like this(of course I didn't consider security stuff):
$sql = "SELECT * FROM hotel where id=".$_GET['id'];
for your table :
Here I just added a tag call detail.php file with parameter id that you can get it in details.php for show details
echo "<tr>
<td><a href="http://yoursite.dev/detail.php?id=".$row["id"]>See Details</a></td>
<td><img src=".$row["hotel_img"]."></td>
<td>".$row["hotel_name"].
"<br />".$row["hotel_address"].
"
</td>
<td>".$row["hotel_phone"].
"
</td>
</tr>";
And in your detail.php file you get parameter id with $_GET['id'] and show more detail for specified id

mySQL statement not running in PHP variable declaration

In the following code I'm attempting to connect to my database, pull the maximum ID from my table and then generate a random number using the the rand() function. The code successfully connects me to the the database but when I try to call for the maximum ID it won't return a value.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) FROM 'table'";
$rannmr = rand(1, $amount);
// Close the mysql connection
mysqli_close($dbLink);
?>
Any help in resolving this would be appreciated.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
Firstly, you are using the wrong identifier for FROM 'table' being single quotes.
If table is indeed the table's name, wrap it in backticks, your question shows file.
$amount = "SELECT MAX(id) FROM `table`";
Either way, you cannot use quotes around a table name. It appears you are using file as your table name.
So if table is only an example and it is called file let's just say, you would do:
$amount = "SELECT MAX(id) FROM `file`";
or
$amount = "SELECT MAX(id) FROM file";
Then, you also need to query, using mysqli_query() which you are not doing.
$amount = mysqli_query($dbLink,"SELECT MAX(id) FROM `file`");
Or Object oriented style:
$amount = $dbLink->query("SELECT MAX(id) FROM `file`");
if($amount){
echo "Success!";
}else{
die('Error : ('. $dbLink->errno .') '. $dbLink->error);
}
See example #1 from http://php.net/manual/en/mysqli.query.php
Use or die(mysqli_error($dbLink)) to mysqli_query() which would have signaled the error.
http://php.net/manual/en/mysqli.error.php
Edit:
Try the following. You may need to modify $row[0] and rand(0,$count) as 1 depending on the column number.
$result = $dbLink->query("SELECT MAX(id) FROM mytable")
while ($row=$result->fetch_row()) { $count = $row[0]; }
$random = rand(0,$count);
echo $random;
use this:
$amount = "SELECT MAX(id) FROM table";
You forgot to execute the MySQL-query:
$amount = $dbLink->query("SELECT MAX(id) FROM table")->fetch_assoc();
$rannmr = rand(1, $amount[0]);
You never executed the query, you need more logic
if ($result = mysqli_query($dbLink, "SELECT MAX(id) as amount FROM `table`")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
if ($row = mysqli_fetch_assoc($result)) {
$amount = $row['amount'];
$rannmr = rand(1, $amount);
}else{
echo 'no row found';
}
}
mysqli_close($dbLink);
I didn't seem to see the line of code which actually does the query:
Try this: Using the object-oriented mysqli approach
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) as max_id FROM 'table'";
// Do the actual query :
$run_query = $dbLink->mysql->query($amount);
// Retrieve the values:
$result = $run_query->fetch_array();
// Do the rand function together with the retrieved value
$rannmr = rand(1, $result['max_id']);
// Now you can echo the variable:
echo $rannmr;
// Close the mysql connection
mysqli_close($dbLink);
?>
Thanks!!

Server error while trying to display data from mysql db in php

I have a database, db_db which I want to display data from in my browser. I have put this php code (display.php) under /var/www/ and trying to access localhost/display.php. Though everytime I come across "Server Error" The website encountered an error while retrieving http://localhost/display.php. It may be down for maintenance or configured incorrectly.
The code is below:
<?php
//make conn
$link = mysql_connect('localhost', 'root', '');
//select db
mysql_select_db('db_db') or die( "Unable to select db");
$sql = "SELECT * FROM results WHERE jobid = 'abc'";
$records = mysql_query($sql);
?>
<html>
<head>
<title> Result Info </title>
</head>
<body>
<table width="600" border = "1" cellpadding = "1" cellspacing= "1">
<tr>
<th>id</th>
<th>name</th>
<tr>
<?php
while($result = mysql_fetch_assoc($records)){
echo "<tr>";
echo "<td>.$result['id'].</td>";
echo "<td>.$result['name'].</td>";
echo "</tr>";
}//end while
?>
</table>
</body>
</html>
Not sure where am I going wrong.
There might be the problem with your database select and query syntax.
Modify your code
<?php
//make conn
$link = mysql_connect('localhost', 'root', '');
//select db
mysql_select_db('db_db', $link) or die( "Unable to select db");
$sql = "SELECT * FROM results WHERE jobid = 'abc'";
records = mysql_query($sql);
?>
Check if it works. Good luck

Simple php + mysql printing a variable from a database

sorry to bother you all but I'm really struggling with this one:
I connect to my database fine and then I try the following mysql statements:
$query1 = "select row1 from mydatabase where row2 = $Name ";
$answer1 = mysql_query($query1);
However, a few lines later when I try :
echo $answer1;
I'm given only nulls :(
Can anyone give me any suggestions please?
edit:
SQL logins:
mysql_connect("correct", "username", "password");
mysql_select_db("dbname") or die(mysql_error());
everything you did is right you have just to fetch the data like this:
$query1 = "select row1 from mydatabase where row2 = $Name ";
$answer1 = mysql_query($query1);
while($data= mysql_fetch_array($answer1)){
echo $data['row1'];
}
And this is a complet answer, i adjust it as you need ;)
<?php
//Connect to your database
$con=mysqli_connect("db_hostname","db_user","db_password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Value of the row to select
$row2 = 'some value';
//Make select query
$result = mysqli_query($con, "SELECT row1 FROM MyTable WHERE row2='$row2'");
//Fetch datas
while($row = mysqli_fetch_array($result))
{
echo $row['row1'];
echo "<br>";
}
//Close database
mysqli_close($con);
?>
Good Luck :)
Try using MySQLi_* instead MySQL_* functions and pass the connection variable to the function calls.
If this doesn't work then you might want to try some further debugging by enabling all error reporting and dumping the global scope.
<?php
error_reporting(E_ALL); // Show all errors & warnings
$conn = mysqli_connect("server", "username", "password");
mysqli_select_db($conn, "dbname") or die(mysql_error());
$sql1 = "SELECT `row1` FROM `mydatabase` WHERE `row2` = '".$Name."';";
$query1 = mysqli_query($conn, $sql1);
$answer1 = mysqli_fetch_assoc($query1);
var_dump($GLOBALS); // Dumps all variables in the global scope
?>
add this after $answer1= mysql_query($query1);
while ($row = mysql_fetch_assoc($answer1)) {
// echo data
echo $row['row1'];
}

MySQL - count total number of rows in php

What is the best MySQL command to count the total number of rows in a table without any conditions applied to it? I'm doing this through php, so maybe there is a php function which does this for me? I don't know. Here is an example of my php:
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("some command");
$row = mysql_fetch_array($result);
mysql_close($con);
?>
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("select count(1) FROM table");
$row = mysql_fetch_array($result);
$total = $row[0];
echo "Total rows: " . $total;
mysql_close($con);
?>
Either use COUNT in your MySQL query or do a SELECT * FROM table and do:
$result = mysql_query("SELECT * FROM table");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";
mysqli_num_rows is used in php 5 and above.
e.g
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("Result set has %d rows.\n",$rowcount);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
Use COUNT in a SELECT query.
$result = mysql_query('SELECT COUNT(1) FROM table');
$num_rows = mysql_result($result, 0, 0);
you can do it only in one line as below:
$cnt = mysqli_num_rows(mysql_query("SELECT COUNT(1) FROM TABLE"));
echo $cnt;
use num_rows to get correct count for queries with conditions
$result = $connect->query("select * from table where id='$iid'");
$count=$result->num_rows;
echo "$count";
for PHP 5.3 using PDO
<?php
$staff=$dbh->prepare("SELECT count(*) FROM staff_login");
$staff->execute();
$staffrow = $staff->fetch(PDO::FETCH_NUM);
$staffcount = $staffrow[0];
echo $staffcount;
?>
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
echo "number of rows: ",$rowcount;
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
it is best way (I think) to get the number of special row in mysql with php.
<?php
$conn=mysqli_connect("127.0.0.1:3306","root","","admin");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="select count('user_id') from login_user";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);
echo "$row[0]";
mysqli_close($conn);
?>
Still having problem visit my tutorial http://www.studentstutorial.com/php/php-count-rows.php
$sql = "select count(column_name) as count from table";
Well, I used the following approach to do the same: I have to get a count of many tables for listing the number of services, projects, etc on the dashboard. I hope it helps.
PHP Code
// create a function 'cnt' which accepts '$tableName' as the parameter.
function cnt($tableName){
global $conection;
$itemCount = mysqli_num_rows(mysqli_query($conection, "SELECT * FROM `$tableName`"));
echo'<h6>'.$itemCount.'</h6>';
}
Then when I need to get the count of items in the table, I call the function like following
<?php
cnt($tableName = 'projects');
?>
In my HTML front end, so it renders the count number
It's to be noted that I create the cnt() function as a global function in a separate file which I include in my head, so I can call it from anywhere in my code.

Categories