while mysql_fetch_array loop doesn't run - php

Here is my code
$itemSelect="select * from items where gender='men' and type='suite'";
$itemQuery=mysql_query($itemSelect) or die(mysql_error());
$num=count($itemQuery);
echo $num;
if($itemQuery)
{
echo "I am here";
echo "<table>";
while($row = mysql_fetch_array($itemQuery))
{
$photo=$row['photo'];
$name=$row['name'];
$price=$row['price'];
echo "<tr><td>". $photo ."</td><td>" .$name ."</td><td>" .$price ."</td> </tr>";
}
echo "</table>";
}
else
{
echo "There is some mistacke";
die();
}
So here $num=count($itemQuery); shows me that there is 1 item that satisfies the search but the loop is never executed what could be the problem? Thanks in advance.

The reason you are getting 1 is because of this code:
$num=count($itemQuery);
echo $num;
count is a function to get the number of items in an array. If you pass anything that isn't an array (or doesn't implement the ICountable interface), then count returns always 1.
So this piece of code is incorrect in that it shows 1, while that number isn't at all related to the number of rows returned.
The query itself looks fine to me, although I cannot validate it against your actual database. If you see the message "I am here", then your query executed fine, but didn't return any rows. If you don't see that message, then something else went wrong. You can use mysql_error to try to find any errors in that case.

$count= mysql_num_rows($itemQuery);
echo $count;
if($count > 0)){
echo "<table>";
while($row = mysql_fetch_array($itemQuery)){
$photo=$row['photo'];
$name=$row['name'];
$price=$row['price'];
echo "<tr><td>". $photo ."</td><td>" .$name ."</td><td>" .$price ."</td> </tr>";
}
echo "</table>";
}else{
echo "there are no results";
die();
}

Related

ELSE condition is not working in the while loop in PHP

<?php
$conn=mysqli_connect("localhost","id6755695_artemi8","sharanod"
,"id6755695_user_info");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$department = $_POST["department"];
$year = $_POST["year"];
$sem = $_POST["semester"];
$reg = $_POST["regulation"];
$sql = "SELECT book_name, author, edition, image FROM dept_search WHERE
department='$department' AND year='$year' AND semester='$sem' AND
regulations='$reg' ";
$result=mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result))
{
if($row)
{
echo "<br>";
?>
<img src=" <?php echo $row['image']; ?> " height="300" width="300">
<?php
echo "<br>";
echo "<b>",$row['book_name'],"</b>";
echo "<br>";
echo $row['author'];
echo "<br>";
echo $row['edition'];
}
else
{
echo "sorry book not found";
}
}
mysqli_close($conn);
?>
please help me with this code,i am building a library management system.. The thing is I should be able to display the books if the given values are present i have in the database if not book not found must be displayed but in while loop after if, else does not runs.....
As others have pointed out, your else statement will never run. If you are already inside the while loop, you will certainly have $row defined and for that reason, else will never run.
What you can do is, check beforehand if the query returned actual results, like so:
$result=mysqli_query($conn,$sql);
if($result->num_rows > 0){
while($row = mysqli_fetch_assoc($result)){
echo "<br>";
?>
<img src=" <?php echo $row['image']; ?> " height="300" width="300">
<?php
echo "<br>";
echo "<b>",$row['book_name'],"</b>";
echo "<br>";
echo $row['author'];
echo "<br>";
echo $row['edition'];
}
}else{
echo "Sorry book not found";
}
You can try with mysqli_num_rows .. sample code as follows :
$rowcount=mysqli_num_rows($conn,$sql);
if($rowcount!=0){
$result=mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result))
{
echo "<br>";
?>
You are looping through all the rows returned from the "mysqli_fetch..." command. Your "if" and "else" is useless -- you will always have rows. If you get no rows, you do not even enter the body of the while loop.
You need to COUNT the rows returned (count($row)) and display a message that nothing was found if the count is less than one.
All you need to do is that you have to change if the condition from if($row) to if($other_condition)
Currently, you are just checking either there is something inside $row, and this condition will never be wrong unless you will assign it null. Because where $row will have something then while loop will be executed, and when while loop will be executed then if condition will be executed.
you have to simply one thing, that is to change if condition like given below...
if($row['value'] == 'something')

Dynamic sort by header in PHP

I'm trying to create a dynamic header on Name which gives the user the ability to sort by ASC or DESC, the results is from the 'register'-table in MySQL. I have tried a couple of codings, but it hasn't given the correct result as of now. Hope anyone is able to help me :)
I have tried making another variable, but I couldn't manage to create the correct one.
<?php
$sql = "SELECT * FROM register";
if($sqlData = mysqli_query($db, $sql)) {
if(mysqli_num_rows($sqlData) > 0) {
echo "<table border ='1' bgcolor='#FFF' width='100%'>";
echo "<tr>";
echo "<th><a href='overview.php?order=name'>Name</a></th>";
echo "<th>Score</th>";
echo "</tr>";
while($row = mysqli_fetch_array($sqlData)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['score'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($sqlData);
} else{
echo "No results in DB";
}
} else{
echo "Error couldn't connect $sql. " . mysqli_error($db);
}
mysqli_close($db);
?>
Hm, that's not a good idea to sort table using MySQL each time user clicked on the table's header.
I suggest you to use javascript for it. Example

Data not required is being displayed

I have a form where the user enters data e.g. AXZAA QS1QS. This data is Posted to my PHP script. The PHP Script connects to a MYSQL database which contains at the moment 2 records.
The idea is that the PHP script will take the input and compare it to the records in the database. If the records exist they are displayed in a table on a web page otherwise, an error message is displayed.
I am having a number of problems with my PHP script and have modified my script a number of times. However, the thing I am having the biggest problem with is this:
When the form appears for the first time, the message record doesn't exist appears twice, this is before the user has entered any data and is seeing the form for the first time. See picture below.
After entering data (when the PHP script was partially working correctly), if there is a match i.e. records existed, along with the records in the table I would receive an error message telling me that records were not found. To see if I could resolve the problem I added code to tell me what records could not be found, the records that couldn't be found were the ones that were found and the other records from the database which I wasn't looking for. I know the SQL query in my PHP script tells the script to get everything from the database however, I would have thought the if statement would have fixed the problem.
Sorry about writing such a long problem and I hope it's not confusing.
enter code here
<?php
//Connect to the database connection file
require 'databaseconnection.php';
$searchBar=(isset($_POST['searchBar']) ? $_POST['searchBar'] :null);
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
?>
Wouldn't it be better to assign $searchbar after an if statement like
`<?php
//Connect to the database connection file
require 'databaseconnection.php';
if(isset($_POST['searchBar']))
{
$searchbar = $_POST['searchBar'];
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
}
else{
echo "<p>Please enter a search term</p>";
}
?>
You could then execute the MySQL query within that "if" statement rather than having it execute assuming there is a value

Limiting column for fetched data in php

I am trying to put extracted mysql data into a table using php. The issue is that I am able to put the fetched data into either all rows or all columns. What I would like to do is put the fetched data into a column format and as soon as 4 columns are used, the next data should start on the next row and so on.
Currently I am using the logic below, however I am getting everything in a column.
The goal is to limit the data to a page size so the data can be printed.
<div>
$result = mysql_query("SELECT * FROM master_data");
echo "<table border='1'>
<tr>
<th>Accounts</th>
</tr>";
echo "<tr>";
while($row = mysql_fetch_array($result))
{
echo "<td>";
echo "First Name:" . $row['First_Name'] . "</br>";
echo "Middle Name:" . $row['Middle_Name'] . "</br>";
echo "Last Name:" . $row['Last_Name'] . "</br>";
echo "</td>";
}
echo "</tr>";
echo "</table>";
mysql_close($con);
?></div>
If I understand your problem correctly you will want to do something like:
Keep a counter to see which number record you're looking at ($i)
$i = 0; // Your counter
while($row = mysql_fetch_array($result))
{
// ...
On every 4th iteration of the loop output something like </tr><tr>.
if ($i % 4 == 0 && $i > 0) // Will return true if `$i` is a multiple of 4 and greater than 0
{
echo "</tr><tr>"; // Output your HTML to start a new row
}
One final note: As others will be pointing out. You should avoid using the MySQL extension. You should use MySQLi or PDO instead.
<div>
$result = mysql_query("SELECT * FROM master_data");
echo "<table border='1'>
<tr>
<th>Accounts</th>
</tr>";
echo "<tr>";
$i = 1;
while($row = mysql_fetch_array($result))
{
if($i == 4)
{
echo "<td>";
echo "First Name:" . $row['First_Name'] . "</br>";
echo "Middle Name:" . $row['Middle_Name'] . "</br>";
echo "Last Name:" . $row['Last_Name'] . "</br>";
echo "</td>";
$i=0;
}
$i++;
}
echo "</tr>";
echo "</table>";
mysql_close($con);
?>
</div>

while loop data doesnt print on screen - PHP

Does anyone see an error in this? I dont get the results printed which is expected from the second loop. How ever the second loop headers are printed without an issue.
I'm trying to print data from a SQL database.
<?php
$con= new mysqli('localhost','root','','regional_data');
if (mysqli_connect_errno()) {exit('Connection failed: '. mysqli_connect_error());}
$result = mysqli_query($con,"SELECT * FROM newchk WHERE dist_chk='$distUsr'");
echo "<table cellpadding='2' class='tablet' cellspacing='0'>";
echo
"<tr>
<th></th>"
."<th>"."Starting Cheque No"."</th>"
."<th>"."Ending Cheque No"."</th>"
."<th>"."Total No of Cheques remaining"."</th>"
."<th>"."Cheque Type"."</th>"
."</tr>";
while ($reca = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td><input type='checkbox' ></td>";
echo "<td>".trim($reca["sbstart"])."</td>";
echo "<td>".trim($reca["sbend"])."</td>";
echo "<td>".trim($reca["totsb"])."</td>";
echo "<td>SB</td>";
echo "</tr>";
}
echo "</table>";
echo "<table cellpadding='2' class='tablet' cellspacing='0'>";
echo
"<tr>
<th></th>"
."<th>"."Starting Cheque No"."</th>"
."<th>"."Ending Cheque No"."</th>"
."<th>"."Total No of Cheques remaining"."</th>"
."<th>"."Cheque Type"."</th>"
."</tr>";
while ($reca = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td><input type='checkbox' ></td>";
echo "<td>".trim($reca["gwstart"])."</td>";
echo "<td>".trim($reca["gwend"])."</td>";
echo "<td>".trim($reca["totgw"])."</td>";
echo "<td>GW</td>";
echo "</tr>";
}
echo "</table>";
$con->close();
?>
</div>
while ($reca = mysqli_fetch_array($result))
This fetches all results from the result set. After that the result set is exhausted, which is why the loop ever ends. There are no more results to be fetched from the same result set afterwards.
Either issue a new query, or save the data into an array which you can loop over again as many times as you want.
I don't think you can use the same $result variable twice.
What I would do is the following:
$result = mysqli_query($con,"SELECT * FROM newchk WHERE dist_chk='$distUsr'");
$result2 = mysqli_query($con,"SELECT * FROM newchk WHERE dist_chk='$distUsr'");
Then your first while loop can use mysqli_fetch_array($result) and the second one can use mysqli_fetch_array($result2).
Hope this helps!

Categories