What is the wrong with "while($row = mysqli_fetch_assoc($result)){// }"? - php

I have tried following code in several ways. but problem is occurred always in "$row = mysqli_fetch_assoc($result)" ..... print_r() method prints the result as an array, that means there is no error with MYSQL query. it gives correct result. problem is in fetch assoc. instead of 'assoc' I have used 'array' as well.
error says "Warning: mysqli_fetch_assoc() expects parameter 1 to be
mysqli_result, array given in
C:\xampp\htdocs\offoptimizer2\action\fetch_client.php on line 21"
class fetch_client{
public function fetchdata(){
$phn_number = $_GET["phn"];
$db_action = new db_action();
$result = $db_action->select_all("offopt_client","client_phn_no='".$phn_number."'");
print_r($result);
echo '<table border="0">';
echo '<tr>';
echo '<th> client name </th>';
echo '<th> client phone number </th>';
echo '</tr>';
if($result != null){
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
echo "<td> ".$row['client_name']." </td>";
echo "<td> ".$row['client_phn_no']." </td>";
echo '</tr>';
}
echo '</table>';
}else{
echo 'No result';
}
}
}
// this is my select_all function below
public function select_all($table_name, $where){
$db_connect = new db_connect();
$con = $db_connect->connect();
if(!$con){
echo "Connection error";
}else{
$query = mysqli_query($con,"select * from ".$table_name." where ".$where." ");
if(!$query){
echo "Error in your query".mysqli_error($query);
}else{
$result = mysqli_fetch_array($query);
return $result;
}
}
}

Uptate your 'select_all' function as below.
public function select_all($table_name, $where){
$db_connect = new db_connect();
$con = $db_connect->connect();
if(!$con){
echo "Connection error";
}else{
$query = mysqli_query($con,"select * from ".$table_name." where ".$where." ");
if(!$query){
echo "Error in your query".mysqli_error($query);
}else{
$result = array();
while($row = mysqli_fetch_assoc($query))
array_push($result, $row);
return $result;
}
}
}
And now, you can use the foreach loop on the result like below:
foreach($result as $row)
echo '<tr>';
echo "<td> ".$row['client_name']." </td>";
echo "<td> ".$row['client_phn_no']." </td>";
echo '</tr>';
}

mysqli_fetch_assoc need a ressource not an array. So this looks like your $db_action->select_all method return your database data in an array, so performing additional task with the result on mysqli functions won't work.
Edit your class behind $db_action if you wish to get assoc return data.

Related

Pulling data from database and into an html table

I'm pulling data from a database but only getting the first row into the dynamically produced html table.
I've tried adding another foreach loop but that isn't the answer… I'm out of ideas...
$conn = new PDO('mysql:host=localhost;dbname=jeuxvideo', $dbUserName, $dbPassword);
$sql = "SELECT * FROM jeuxvideo";
$result = $conn->prepare($sql);
$request = $result->execute();
echo "<table border='1'>";
echo "<tr><td>Id</td><td>Titre</td><td>Prix<td>Date de Sortie</td><td>Genre</td><td>Origine</td><td>Mode</td><td>Connexion</td></tr>\n";
$row = $result->fetch(PDO::FETCH_ASSOC);
echo "<tr>";
foreach ($row as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
echo "</table>";
This code pulls all the correct info and puts it in the right place in the html table, but for some Reason it doesn't collect the Following rows data...
This line only fetches one row:
$row = $result->fetch(PDO::FETCH_ASSOC);
You need to fetch as many rows it can give you. Once there are no more rows to fetch the function will return FALSE, so you can use with the while loop, like this:
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
foreach ($row as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
}
echo "</table>";
Since you don't have any variables you need prepared for your query, you can simply do:
<?php
$stmt = $pdo->query('SELECT * FROM jeuxvideo');
echo '<table>';
foreach ($stmt as $row) {
echo '<tr>';
echo "<td>$row['name']</td>";
echo "<td>$row['url']</td>";
echo "<td>$row['timestamp']</td>";
echo '</tr>';
}
echo '</table>';
A 2nd method would be:
<?php
$stmt = $pdo->query('SELECT * FROM jeuxvideo');
echo '<table>';
while ($row = $stmt->fetch()) {
echo '<tr>';
echo "<td>$row['name']</td>";
echo "<td>$row['url']</td>";
echo "<td>$row['timestamp']</td>";
echo '</tr>';
}
echo '</table>';
Try this
$conn = new PDO('mysql:host=localhost;dbname=jeuxvideo', $dbUserName, $dbPassword);
$sql = "SELECT * FROM jeuxvideo";
$result = $conn->prepare($sql);
$request = $result->execute();
echo "<table border='1'>";
echo "<tr><td>Id</td><td>Titre</td><td>Prix<td>Date de Sortie</td><td>Genre</td><td>Origine</td><td>Mode</td><td>Connexion</td></tr>\n";
$row = $request->fetch_all();
echo "<tr>";
foreach ($row as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
echo "</table>";

how to output mysql table data into an html table without knowing what $row is like phpmyadmin

Ok so I'm trying to make a localhost site that has the same base functions as Phpmyadmin, and everything is working other than displaying a table's data.
here's an example of what I'm trying to accomplish:
though I'm not sure how to accomplish this. Here is some code to show you what I have now
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$columquery = "SHOW COLUMNS FROM " . $table;
$columresult = mysql_query($columquery);
while ($row3 = mysql_fetch_array($columresult)) {
echo "<th>" . $row3['Field'] . "</th>";
}
?>
<?php
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($result2)) {
foreach($row2 as $var) {
echo "<tr><td>" . $var . "</td></tr>";
}
}
?>
</table>
</div>
Yes yes, I know it's horrible.
The other answers use the mysqli API while you're using the older, no longer supported mysql API. I really recommend upgrading to either mysqli or PDO, but if you want to stay with mysql you can use the following solution:
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$shouldOutputHeaders = true;
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_assoc($result2)) {
if ($shouldOutputHeaders) {
echo "<tr>";
foreach (array_keys($row2) as $header) {
echo "<th>" . $header . "</th>";
}
echo "</tr>";
$shouldOutputHeaders = false;
}
echo "<tr>";
foreach ($row2 as $var) {
echo "<td>" . $var . "</td>";
}
echo "</tr>";
}
?>
</table>
</div>
If i understood you well, You need mysqli_fetch_row.
$q= "SELECT * FROM table";
$result = $mysqli->query($q)
while ($row = $result->fetch_row()) {
print ("$row[0], $row[1]);
}
I think you are looking for something very ugly like the following. I found it in the garbage. I am not responsable for any use of it:
<?php
$db=Db::getConnection(); // singleton
$this->var['result']=$db->query($_POST['query']);
if (isset($this->var['result'])) {
echo '<table cellpadding="5" cellspacing="2" border="1"><tbody>';
$titles=array_keys(#$this->var['result'][0]);
echo '<tr>';
foreach($titles as $title)
echo '<th>'.$title.'</th>';
echo '</tr>';
foreach($this->var['result'] as $row) {
echo '<tr>';
foreach($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
}
?>
Db is an standard singleton that contains a mysqli private object.
query() contains something like
$sql = $this->mysqli->query($query);
$this->lastInsertId = $this->mysqli->insert_id;
$errno = $this->mysqli->connect_errno;
if ($errno === 0) {
if ($this->mysqli->field_count > 0) {
while ($row = $sql->fetch_assoc()) $response[] = $row;
return $response;
}else{
return true;
}
}
to create the "array of arrays" response. Suitable for the output you are looking for.
I've added some escaping and only queried the database when needed:
// Print table tags
echo "<table>";
// Print out records
$q = mysql_query("SELECT * FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print out columns
$columns = array_keys($res[0]);
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$columns).'</th></tr>';
// Print out table data
echo'<tr><td>'.implode('</td><td>', array_map('htmlspecialchars',$res).'</td></tr>';
} else {
// IFF there is no data, print out columns
$q = mysql_query("SHOW COLUMNS FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print columns
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$res).'</th></tr>';
}
}
echo '</table>';
Hope this helps,

Can't display my result in a table - PHP

I am trying to display my query results on page. However, whenever I run the code although the query is correct it does not display anything.
Can anyone help? Would be muchly appreciated
<?php
session_start();
require_once("../config1.php");
if(isset($_POST["DailySales"])) {
$linkid = mysqli_connect(DB_DATA_SOURCE, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die("Could not connect:" . connect_error());
$sql = "SELECT Retdatetime AS date , sum(rentalrate + overduecharge) AS mny
FROM frs_FilmRental
WHERE shopid='2'
Order BY retdatetime DESC ";
$result = mysqli_query($linkid, $sql);
if (!$result)) {
printf("Errormessage: %s\n", mysqli_error($linkid));
}
echo "<table border = '1' align='center'>";
echo "<th> Shop ID 2</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<h2><center>Shop ID 2 daily sales : </center></h2>";
echo "<tr><td>";
echo $row['mny'];
echo "</td><td>";
echo $row ['date'];
echo "</td></tr>";
}
}
?>
replace
echo $row ['date'];
by
echo $row ['Retdatetime'];
To understand query errors you should use mysqli_error() in your code. If there are no errors for executed query, then you can run while loop for it.
<?php
session_start();
require_once("../config1.php");
if(isset($_POST["DailySales"])) {
$linkid = mysqli_connect(DB_DATA_SOURCE, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die("Could not connect:" . connect_error());
$sql = "SELECT Retdatetime , sum(rentalrate + overduecharge) AS mny
FROM frs_FilmRental
WHERE shopid='2'
Order BY retdatetime DESC ";
$result = mysqli_query($linkid, $sql);
if (!$result)) {
printf("Errormessage: %s\n", mysqli_error($linkid));
} else {
echo "<table border = '1' align='center'>";
echo "<tr><th> Shop ID 2</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<h2><center>Shop ID 2 daily sales : </center></h2>";
echo "<tr><td>";
echo $row['mny'];
echo "</td><td>";
echo $row ['date'];
echo "</td></tr>";
}
echo "</table>";
}
}
?>
fixes given in comments also applied
Please copy/paste the error, given by mysqli_error()

PHP: While loop does not run when the condition is true

The following PHP program is to search for a student number in database and display the details if found or give a message if it does not exist.
<html>
<body>
<?php
$sno=$_POST['studNo'];
$connection = mysql_connect("localhost", "root", "")
or die("couldn't connect to the server");
$db = mysql_select_db("student", $connection)
or die("<b>connection fails");
$query = "select * from performance where Number = '$sno'";
if($result = mysql_query($query))
{
echo "<table border = 1 align = center>";
echo "<tr>";
echo "<th>Number<th>Name<th>Address<th>Mobile Number";
echo "</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<th>",$row['Number'],"</th>";
echo "<th>",$row['Name'],"</th>";
echo "<th>",$row['Address'],"</th>";
echo "<th>",$row['MobileNo'],"</th>";
echo "</tr>";
}
echo "</table>";
echo "The student data updated";
}
else
{
echo "<b>Customer number does not exist";
}
mysql_close($connection);
?>
</body>
</html>
If i search for a number which does not exist the else block runs. When i give a number which exists then the if block runs but the while loop does not run. Can anybody help me out? Database field names are correct.
mysql_query() only returns false if there's an error in the query. Not finding any matching rows is not an error. To tell if any rows were found use mysql_num_rows().
$result = mysql_query($query) or die("Query error: " . mysql_error());
if (mysql_num_rows($result) > 0) {
...
} else {
echo "<b>Customer number does not exist</b>";
}

Displaying "No Results Found" in PHP

Good day!
I am having trouble displaying a "No records found" message in my PHP process.
Here is the code for my search query:
if(isset($_GET['submit'])) {
$product = $_GET['product'];
$city = $_GET['city'];
$query = "SELECT * FROM $product WHERE city = '$city'";
$result = mysqli_query($con, $query) or die ("Could not connect to database.");
$product = str_replace('_', ' ', $product);
$product = strtoupper($product);
echo "You have searched for " . $product . " in " . $city;
echo "<table border=1>";
echo "<tr> <th>Store</th> <th>City</th> </tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr><td>";
echo $row['store'];
echo "</td><td>";
echo $row['city'];
echo "</td></tr>";
}
echo "</table>";
}
My problem is I don't know where and what to place the conditional statement that will show "No records found".
Hoping that someone would be able to help me on this one.
Thanks in advance.
check if the number of rows in the result is 0 via mysqli_num_rows function and display the message before looping over the result set.
your code could be like
if(isset($_GET['submit'])) {
$product = $_GET['product'];
$city = $_GET['city'];
$query = "SELECT * FROM $product WHERE city = '$city'";
$result = mysqli_query($con, $query) or die ("Could not connect to database.");
$product = str_replace('_', ' ', $product);
$product = strtoupper($product);
echo "You have searched for " . $product . " in " . $city;
echo "<table border=1>";
// check if results are present
if(mysqli_num_rows($result)>0) {
echo "<tr> <th>Store</th> <th>City</th> </tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr><td>";
echo $row['store'];
echo "</td><td>";
echo $row['city'];
echo "</td></tr>";
}
} else {
echo "<tr> <td colspan='2'> No Results found </td></tr>";
}
echo "</table>";
}
You should try this code , if any error any code in you code then you can find that.
$result = mysqli_query($con, $query) or die(mysqli_error($con));
OR
if(!$result){
echo die(mysqli_error($result));
}
The mysqli_affected_rows() function returns the number of affected rows in the previous SELECT, INSERT, UPDATE, REPLACE, or DELETE query.
Aslo from reference:http://php.net/manual/tr/mysqli.affected-rows.php
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records were updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.
$product = $_GET['product'];
$city = $_GET['city'];
$query = "SELECT * FROM $product WHERE city = '$city'";
$result = mysqli_query($con, $query) or die ("Could not connect to database.");
$product = str_replace('_', ' ', $product);
$product = strtoupper($product);
echo "You have searched for " . $product . " in " . $city;
if(mysqli_affected_rows($con) ==0){ echo "No records found"; }
else{
echo "<table border=1>";
echo "<tr> <th>Store</th> <th>City</th> </tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr><td>";
echo $row['store'];
echo "</td><td>";
echo $row['city'];
echo "</td></tr>";
}
echo "</table>";
}

Categories