I'm having a problem with some specific PHP code that I've been working on for a few days. It's meant to be a reporting code where I can input a day and a month and it will list the total sales of that particular day.
But, I can't seem to make the last statement whereby, if there are no values(there are no data) in the query, it will display 'No Sales on this particular day'. Here's the code I've been working on. But the last echo statement is not executing. Any ideas?
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
$day=#$_POST['day'];
$month=#$_POST['month'];
echo "<center><h2>Sales report on " .$day. "." .$month. ".2013</h2></center>";
echo "<center><table style='border:2px solid black;' align=center width=600>";
echo "<tr><th colspan=12><center><h2>Sales Report</h2><hr size='2' color='black' /></center></th></tr>";
echo " <th width=400> Amount Collected</th>";
?>
<br>
<?php
$x = 1; //counter
//open a connection to a MySQL server using function mysql_connect
//returns a MySQL link identifier on success, or FALSE on failure.
$conn= mysql_connect("localhost","root","");
if (!$conn)
die ("Connection error: ".mysql_error());
else {
//select a MySQL database
//returns TRUE on success or FALSE on failurue.
$db=mysql_select_db("cqfos");
if(!$db)
die ("DB not found: ".mysql_error());
else {
//put query in a variable $query
$query= "select ROUND(sum(orderdetails.tprice),2)
from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '$day' AND MONTH(orders.date) = '$month'";
$result=mysql_query($query);
if(!$result)
die ("Invalid query: ".mysql_error());
//if record exists
else {
//fetch a result row as both associative array and numeric array
if(mysql_num_rows($result)== 1){
while ($row=mysql_fetch_array($result,MYSQL_BOTH)){
echo "<tr>";
echo "<td align='center'>RM ".$row[0]."</td></tr>";
$x++; //increase the counter
}
}
else {
echo "<tr><th colspan=12>No sales made.</td></tr>";}
}
}
}
echo"</table></center>";
?>
Several problems here
your HTML table syntax is incorrect, and your using an old sql library - and it dose not look like your SQL syntax is right... try this code (not tested as I don't have your data)
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
echo '<div style="margin:auto; textalign:center;">';
echo "<h2>Sales report on " .$_POST['day']. "." .$_POST['month']. ".2013</h2>";
echo "<h2>Sales Report</h2>"
echo "<table style='border:2px solid black;' align=center width=600>";
echo "<tr><th width=400> Amount Collected</th></tr>";
?>
<br>
<?php
$conn = new mysqli("localhost","root","","cqfos");///use mysqli, not mysql : mysql is depricated
if ($conn->mysqli)
exit ("Connection error: ".$conn->errno ." : " $conn->error);
else {
//put query in a variable $query
$eDay = $conn->mysql_real_escape_string($_POST['day']);//escape these to protect the database
$eMonth = $conn->mysql_real_escape_string($_POST['month']);;//escape these to protect the database
//your column name is probably not a rounded value, replaced it with * (return all columns)
$query= "select * from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '"
.$eDay."' AND MONTH(orders.date) = '".$eMonth."'";
$result=$con->query($query);
if($conn->errno)
exit ("Invalid query: ".$conn->errno ." : " $conn->error);
//if record exists
else {
$numericArray = $result->fetch_array(MYSQLI_NUM); //fetch a result row as numeric array
$associativeArray = $result->fetch_array(MYSQLI_ASSOC); //fetch as an associtive array this is not used, just an example
$bothArray = $result->fetch_array(MYSQL_BOTH); //both associtive and numeric this is not used, just an example
}
if(!empty($numericArray))
{
foreach ($numericArray as $value) {
echo "<tr><td>RM ".$value[0]."</td><tr>";//is there more then 1 col? if not you should consider an html list
}
} else {
echo "<tr><td>No sales made</td><tr>";
}
echo"</table></center>";
}
?>
Your SQL (likely) returns more than only one row, so change the line I mentioned before to this:
if(mysql_num_rows($result)>0){
Just letting you know your code is vulnerable to SQLi because you have not sanitized $day and $month. Also please consider using PDO.
If you haven't already - Try running the SQL statement into PHPMyAdmin and see where it outputs the error (if there is one), else it will output the data.*
*Manually inputting the day/month substituting for the variables.
Related
I had a very random problem in an IIS class, it has stumped my tutor so here I am and I'll try my best to explain it well!
I'm running Xampp with Apache and MySQL, I run the query I want and get the expected output to a table, but I have a problem with the outputting of pictures. I have the right file type, extention and path selected, because I can get pictures to show up, but as long as at least one picture in the query result has the extension removed, and this picture will not load.
Database
Website
If I have each query result with the correct name and extension, which is the same as when it shows up, none of them show up at all!
PHP:
<?php
// set server access variables
include 'db2.inc';
// open connection
$connection = mysql_connect($hostname, $username, $password) or die ("Unable to connect!");
// select database
mysql_select_db($databaseName) or die ("Unable to select database!");
// create query
//$query = "SELECT * FROM products";
$query = "SELECT * FROM products WHERE CategoryName = 'Surfboards'";
//Check initial letter
//if (!$initialLetter=="")
//{
// $query = $query." Where country like '$initialLetter%' ";
//}
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<table cellpadding=20 border=1>";
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['ProductID']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['Description']."</td>";
echo "<td>".$row['Brand']."</td>";
echo "<td>".$row['Model']."</td>";
echo "<td>".$row['BoardLength']."</td>";
echo "<td>".$row['BoardType']."</td>";
echo "<td>".$row['Colour']."</td>";
echo "<td>"."<img src=images/".$row['Image']."> </td>";
echo "<td>".$row['UnitPrice']."</td>";
echo "<td>".$row['CategoryName']."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
Any help or direction would be greatly appreciated!
Thanks
Will
On this line:
echo "<td>"."<img src=images/".$row['Image']."> </td>";
Your image src is not enclosed in quotes. If this is a direct copy/paste of your code then that is definitely a problem, but may not be the only one.
As other people have said, look at pdo, or mysqli. The mysql_ functions you are using are deprecated for multiple reasons.
I want to insert a html code in between MySQL results.
My query
if($sql = $mysqli->query("SELECT * FROM table Limit 20")){
$row = mysqli_fetch_array($sql);
//Results display here
$sql->close();
}else{
printf("There seems to be an issue. Please Trey again");;
}
Above query is pulling 20 results at a time. I want to insert <div class="block"></div>after pulling 3rd result and continue other results after that div (using a single query)
Can anyone point me how to do this.
As it simple as it gets.
You just have to count each iteration and when it reaches 3 you print out the div element.
<?php
$mysqli = new mysqli("localhost","","","");
if ($mysqli->connect_errno){
echo "Failed to connect to MySQL";
}
if ($result = $mysqli->query("SELECT * FROM table")) {
$counter = 0;
while ($row = $result->fetch_assoc()) {
echo $row["______"];
if((++$counter) == 3) {
echo '<div class="block"></div>';
}
}
$result->close();
}
$mysqli->close();
?>
i have a cart displayed and the user has to select the date of delivery from the calendar widget and click on Confirm button. on submit, the order cart should be populated along with the entered date of delivery.
the code i used is:
<?php
echo "<form action='' name='form1' >";
//some disaply codes here
echo "Choose the Date of delivery<input type='date' name='date'>";
echo "<input type='submit' class='btn btn-default' name='final_submission' value ='Confirm Order'>";
echo "</form>";
?>
the code for insertion is:
<?php
if (isset($_POST['final_submission'])){
error_reporting(E_ALL);
ini_set('display_errors', 1);
$IP="my localhost";
$USER="my user name";
$conn=mysqli_connect($IP,$USER,"","my database name");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = stripslashes($_POST['date']);
$result=mysqli_query($conn, $query);
$query="select * from cart";
while($row = mysqli_fetch_array($result)) {
$us_id=$row['user_id'];
$pr_id=$row['prod_id'];
$qtty=$row['quantity'];
$query_insert = "insert into orders(user_id, prod_id, quantity, dt_del) values('.$us_id.',
'.$pr_id.', '.$qtty.','.$date.')";
$res_ins=mysqli_query($conn,$query_insert);
}
}
?>
the orders table s not getting populated. I cant put my finger on the error. plz point it out
EDIT: the orders table is getting poplulated, but the del date field is coming blank...Please let me know how to pass the date variable correctly, as clearly that is the issue
I am not sure what you are trying to attempt to be honest. Your code blocks lacks a lot of stuff. For instance:
$query="select * from cart";
while($row = mysqli_fetch_array($result)) {
What results? Where do you define them? Are that results from the query you specified there, cause surely you aint executing it. Thus the result will be 0 and will not be executed.
Also the problem is with this query it will go through every row of the cart, this means also you ll grab carts that aint belonging to your costumer, specify.
So your code should be something like
$query="select * from cart";
$result = mysqli_query($conn,$query);
while($row=mysqli_fetch_array($result)){
// yadi yadi yadi .. code code code
edit
Let me try to rework this out for you with propper indenting.
if (isset($_POST['final_submission'])){ // check if the button is correct
// error_reporting(E_ALL); <-- canceling this out for now
// ini_set('display_errors', 1); <-- canceling this out for now
$IP="my localhost";
$USER="my user name";
$conn=mysqli_connect($IP,$USER,"","my database name");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = stripslashes($_POST['date']);
if (empty($date) || $date == ''){
echo 'the date is not set, please check if parameter is filled in';
} else { // if it wont pass this point, you wont get an enormous output of unidentified indexes
$query="select * from cart";
$result=mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)) {
$us_id=$row['user_id'];
$pr_id=$row['prod_id'];
$qtty=$row['quantity'];
$date = stripslashes($_POST['date']); // just to play it safe define it again
if (empty($date) || $date == ''){
echo 'something went wrong with the date';
}else{
$query_insert = "insert into orders(user_id, prod_id, quantity, dt_del) values('.$us_id.','.$pr_id.', '.$qtty.','.$date.')";
$res_ins=mysqli_query($conn,$query_insert);
}
}
}
}
I want to make a code that check if a value in an exact column is equal to an 'neodobren', and if there is such value in the column to echo out the button 'Add Member' and Yes for each value. I've tried to do the following and it is not echoing the Yes:
I have the following MySQL table content:
UID Name Phone Email SchoolGymnasium City Password Status
1 neodobren
2 neodobren
and I have the following PHP code inside the HTML index page:
$con = mysql_connect("localhost","****","****");
mysql_query("SET NAMES UTF8");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("***", $con);
include("../../sql.php");
session_start();
$zaqvki = mysql_query("SELECT * FROM Directors WHERE Status='neodobren' LIMIT 1");
if(mysql_num_rows($zaqvki) > 0) {
echo '<div align="right">Add Member</div><br>';
// display data in table
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array($zaqvki)) { //$zaqvki was $result, before a guy comment me this...
echo "Yes";
} }
else {
echo "No";
}
It is showing only the button add member, and not showing the Yes, which must be echo-ed.
Use mysql_fetch_assoc to get an associative array and make a comparison on each row of a certain column:
while($row = mysql_fetch_assoc($result))
{
if($row['Status'] === 'neodobren')
echo "Yes";
else
echo "No";
}
I'm trying to retrieve all data with the LIKE query from the users input and match it to the database, it works but only returns one record but I have many records in the table.
It returns the closest record it can find,
so say for example I have 2 records who's ItemDesc field contains the characters 'The', when I search for 'The' in my input box and click submit it returns the closest (earliest created) record when it is supposed to return both.
<?php
$username = "a3355896_guy";
$password = "++++++";
$hostname = "mysql5.000webhost.com";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db("a3355896_book") or die("Unable to connect to database");
$ItemDesc = $_POST['ItemDesc'];
$query = "select * from StockItems where ItemDesc LIKE '%$ItemDesc%'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
mysql_close();
?>
Sorry was supposed to included the retrieval:
<?php
if ($num>0)
{
echo "<center><table border=1><tr><th>Item Code</th><th>Item Desc</th>";
echo "<th>Item Stock Qty</th>";
echo "<th>Item Unit Price</th><th>Item Category</th></tr>";
$ItemCode = mysql_result($result,$i,"ItemCode");
$ItemDesc = mysql_result($result,$i,"ItemDesc");
$ItemStockQty = mysql_result($result,$i,"ItemStockQty");
$ItemUnitPrice = mysql_result($result,$i,"ItemUnitPrice");
$ItemCategory = mysql_result($result,$i,"ItemCategory");
echo "<tr><td>$ItemCode</td><td>$ItemDesc</td><td align=right>";
echo "$ItemStockQty</td>";
echo "<td align=right>$ItemUnitPrice</td>";
echo "<td>$ItemCategory</td></tr>";
echo "</table></center>";
}
else
{
echo "<form name='DeleteStock2'>";
echo "<p> Sorry, $ItemDesc does not exist!<p>";
echo "<input type='button' value='Leave' onclick='history.go(-1)'>";
}
?>
You aren't actually accessing your data here- you need to iterate over the result set.
$setLength = mysql_num_rows($result);
for($i = 0; $i < $setLength; $i++){
//Here, mysql_fetch_assoc automatically grabs the next result row on each iteration
$row = mysql_fetch_assoc($result);
//do stuff with "row"
}
Unless you ARE doing that and you just chose to not include it in your snippit. Let us know :)
--Edit--
First off, I apologize- out of old habit I suggested that you use mysql_fetch_assoc instead of the mysqli set of functions.
Try using the fetch_assoc or fetch_array functions, it could solve your issue. I've never used the method you used, I think it has been deprecated for a while.
Check it out here:
http://php.net/manual/en/mysqli-result.fetch-assoc.php