Php / Mysql While Loop Error - php

Okay, none of those responses I used but I fixed it myself.
Im having trouble though trying to sum up all the prices for the books:
Code:
<style type="text/css">
table{font-size:1.11em;}
tr{background-color:#eee; border-top:1px solid #333;}
</style>
<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bookorama", $con);
$sql="SELECT customers.name, books.title, books.isbn, books.price
FROM customers, orders, order_items, books
WHERE customers.customerID = orders.customerID
AND orders.orderID = order_items.orderID
AND order_items.isbn = books.isbn;";
$result = mysql_query($sql); // You actually have to execute the $sql with mysql_query();
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
echo "<h1 style='color:#3366ff;'>Each customer book orders</h1>";
echo "<table>"; //start the table
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) //Loop through the results
{
//echo each row of the table
echo "<tr>";
echo "<th><strong>Customer Name:</strong><br></th>";
echo "<td>$row[name]</td>";
echo "<th><strong>Book Title</strong><br></th>";
echo "<td>$row[title]</td>";
echo "<th><strong>ISBN</strong><br></th>";
echo "<td>$row[isbn]</td>";
echo "<th><strong>Book Price</strong><br></th>";
echo "<td>$row[price]</td>";
echo "</tr>";
}
echo '</table>'; //close out the table
?>

mysql_query returns FALSE on error, and you didn't check for this before trying to pass it to mysql_fetch_array.
You really should put error checking in your code!

Well maybe $result contains false because of error, add this block after mysql_query call.
if (!$result) {
die('Invalid query: ' . mysql_error());
}

Because your call $result = mysql_query($sql); has an error and returns false. You need to check for errors before you try to use a resource:
$result = mysql_query($sql);
if( !$result ) {
echo "SQL Query failed! " . mysql_error();
}
else {
// rest of your code here
}

Related

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

Struggling with php SELECT

I have used the below code in my website,
<?php
$con= mysqli_connect("*******","******","*****", "catalejo_articles");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result= mysqli_query($con, "SELECT * FROM baul");
while($row = mysqli_fetch_array($result))
{
echo $row['title'] . " " . $row['date'];
}
mysqli_close($con);
?>
and it is not working. What am i doing wrong??
I am new to php and mysql, any help will be appreciated.
UPDATE:
I want to thank and apologize to all of you who spent precious time trying to help me. I just solved the problem, the original code was OK. The problem was I didn't change the file extension to PHP.
Make sure display error is enabled. add this line at the top of your page and see if it display any error :
error_reporting(-1);
And try inside while loop :
var_dump($row)
Does table contains data?
Try this way,
if ($result = mysqli_query($con, "SELECT * FROM baul", MYSQLI_USE_RESULT)) {
while($row = mysqli_fetch_array($result))
{
echo $row['title'] . " " . $row['date'];
}
mysqli_free_result($result);
}
Check if u have any records in your table using mysqli_num_rows
$con= mysqli_connect("*******","******","*****", "catalejo_articles");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result= mysqli_query($con, "SELECT * FROM baul");
$count = mysqli_num_rows($result);
if($count > 0)
{
while($row = mysqli_fetch_array($result))
{
echo $row['title'] . " " . $row['date'];
}
}else{
echo "No Records found in the table";
}
mysqli_close($con);
From what I can make out of your code, since you were attempting to reference by association instead of by numerical index, you weren't seeing anything because you were missing MYSQLI_ASSOC in your while loop:
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo $row['title']." ".$row['date'];
}
Otherwise you need to know where "title" and "date" columns are located and reference them by numerical value:
while($row = mysqli_fetch_array($result)) {
echo $row[0]." ".$row[1];
}
Alternatively, if mysqli_fetch_array is not working (due to PHP version), try using:
while($row = mysqli_fetch_assoc($result)) {
echo $row['title'].' '.$row['date'];
}

Only Displaying one row Mysql

I want this data to display all the results, in the query I get 129 results. But when I display it on the page I only get one row. I have used very similar code to get multiple results before, so I know it`s something simple, but I just can't get it. Any thoughts would be greatly appreciated!
<?php
$sql = "SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber";
$sql1 = "select dataplan as currentplan from maindata GROUP BY phonenumber";
$sql2 = "SELECT DISTINCT phonenumber AS value_sum1 FROM maindata";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
$result1 = mysql_query($sql2);
if (!$result1) {
echo "Could not successfully run query ($sql1) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result1) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
$result2 = mysql_query($sql2);
if (!$result2) {
echo "Could not successfully run query ($sql2) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result2) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)){
echo "<TABLE id='display'>";
echo "<td><b>Data Usage This Period: ". ROUND ($row["value_sum"],2) . "MB</b></td> ";
}
while ($row1 = mysql_fetch_assoc($result1)){
echo "<TABLE id='display'>";
echo "<td><b>Data Plan: ". $row1["currentplan"] . "</b></td> ";
}
while ($row2 = mysql_fetch_assoc($result2)){
echo "<TABLE id='display'>";
echo "<td><b>Phone Number: ". $row2["value_sum1"] . "</b></td> ";
}
?>
Updated based on suggestions - Very helpful thank you, I am very close, all values are correct but I can not get them in the same table, thoughts?
TRY To use ,
Loop in you code eg.
$result1 = mysql_query("SELECT DISTINCT phonenumber AS value_sum1 FROM maindata");
echo '<table>';
echo '<tr>';
echo '<th>id</th>';
echo '</tr>';
while($record = mysql_fetch_assoc($result))
{
echo '<tr>';
foreach ($record as $val)
{
echo '<td>'.$val.'</td>';
}
echo '</tr>';
}
echo '</table>';
Add
"LIMIT 0, 1" at the end of query
or
edit query like "select TOP 1 from....."
Lets make it easy on you ;)
have a look here how to use mysql_fetch_assoc
http://php.net/manual/en/function.mysql-fetch-assoc.php
follow the examples, you will be done in a sec.

How to Post data from a php database populated Drop Down to another script?

I created a PHP Drop Down which is populated from a MySql Database and works just fine, the problem occurs when I want to post the selected in another script. The question is how to post the data to the other script?
This is the source code of the script that implements the drop downs. Please Help!!!!
<?php
$conn = mysql_connect("localhost", "admin", "admin");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("ekupuvac")) {
echo "Unable to select EKupuvac: " . mysql_error();
exit;
}
$query = "SELECT ImeK, KupuvacID FROM kupuvac ORDER BY Saldo DESC";
$result = mysql_query($query) or die(mysql_error());
if (!$result) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so I am exiting";
exit;
}
$dropdown = "<select name='ImeK'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown.= "\r\n<option value='{$row['KupuvacID']}'>{$row['ImeK']}</option>";
}
$dropdown .= "\r\n</select>";
echo"Izberi Kupuvac:";
echo $dropdown;
// Second Combo
$conn = mysql_connect("localhost", "admin", "admin");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("ekupuvac")) {
echo "Unable to select EKupuvac: " . mysql_error();
exit;
}
$query2 = "SELECT ImeP, ProzivodID FROM proizvod ORDER BY ImeP";
$result2 = mysql_query($query2) or die(mysql_error());
if (!$result2) {
echo "Could not successfully run query ($query2) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result2) == 0) {
echo "No rows found, nothing to print so I am exiting";
exit;
}
$dropdown2 = "<select name='ImeP'>";
while($row = mysql_fetch_assoc($result2)) {
$dropdown2.= "\r\n<option value='{$row['ProzivodID']}'>{$row['ImeP']}</option>";
}
$dropdown2.= "\r\n</select>";
echo"<br> Izberi Proizvod:";
echo $dropdown2;
echo"<br>";
mysql_free_result($result);
?>
A <select> box is not enough, you need to enclose it in a form
?>
<form method="post" action="somescript.php">
<?
//your controls go here
?>
</form>
then create somescript.php and access your form variables using $_POST
Also use PDO not mysql_ functions as these arent safe

Fetch information from mysql db using php

Updated script with proper field names. Why isnt this working?
<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bookorama", $con);
$sql="SELECT * FROM customers";
$result = mysql_query($sql); // You actually have to execute the $sql with mysql_query();
echo "<table>"; //start the table
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) //Loop through the results
{
//echo each row of the table
echo "<tr>
<td>$row['customerID']</td>
<td>$row['name']</td>
<td>$row['Aaddress']</td>
<td>$row['city']</td>
</tr>";
}
echo '</table>'; //close out the table
?>
<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bookorama", $con);
$sql="SELECT * FROM customers";
$result = mysql_query($sql); // You actually have to execute the $sql with mysql_query();
echo "<table>"; //start the table
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) //Loop through the results
{
//echo each row of the table
echo "<tr>";
echo "<td>$row['CustomerID']</td>";
echo "<td>$row['address']</td>";
echo "<td>$row['city']</td>";
echo "</tr>";
}
echo '</table>'; //close out the table
?>
You can mysql_fetch_array or mysql_fetch_assoc to retriever the rows from you query.
For example using mysql_fetch_array:
$result = mysql_query($sql);
echo "<table><tbody>";
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "<tr><td>".$row[0] . "</td><td>" . $row[1] . "</td></tr>";
}
echo "</tbody></table>"
You need to run the query and loop through the results.
You are better off learning from day one about PDO.
And also don't interpolate directly from any user submitted variables (that includes $_POST).
Pretty sure you need to do this when embedding anything more complex than scalars inside double quotes
echo "<tr>
<td>{$row['CustomerID']}</td>
<td>{$row['address']}</td>
<td>{$row['city']}</td>
</tr>";
So whenever you have a more complex var name than "test $var" in quotes, wrap with {} - and even then, it's good practice to wrap scalars too like "test {$var}"

Categories