If there is data the first part works great. When there are no $res the else portion is not echoing.
IO have tried using this but the ! $row stops and will not echo anything inside. so I rewrote it to the php script below which is more straight forward. I was now that worried about sql injection since I am cleaning id as well as verifying the user is actually logged into the system.
$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if( ! $row)
{
die('nothing found');
}else {
enter code here
}
Thjs is my entire php page.
$db = new PDO (connection string. )
<?php
error_reporting(0);
include_once("php_includes/db_conx.php");
if($_GET['id'] != ''){
$id = preg_replace('#[^0-9]#', '', $_GET['id']);
$sql="SELECT nextdue, alert, completed, page_id, page_type FROM medical where id=$id limit 1";
$alertdiv = "";
if ($res = $db->query($sql)) {
$alertdiv = "";
foreach( $db->query($sql) as $data ) {
//if alert is set to Y create div to show the type and stuff.
$timestamp = $data[0];
if ($data[1]=='y'){
if($timestamp > date("Y-m-d")) {
$alertdiv .= "This alert is in the Future.<br>";
}
if($timestamp < date("Y-m-d")) {
$alertdiv .= "This alert is pastdue.<br>";
}
if($timestamp == date("Y-m-d")) {
$alertdiv .= "This alert is due Today.<br>";
}
$alertdiv .= "<table><tr><td width='50'>Method</td><td>Description</td><td>Destination</td><td>Completed</td><td>Date Due</td><td>Action</td></tr><br>";
$completed = $data[2];
$page_id = $data[3];
$page_type = $data[4];
//check completed
//get page details
switch ($page_type) {
case "d":
$alertdiv .= "<tr id='selectedmethodtr' value='d0'>";
$alertdiv .= "<td width='10'>Default</td><td>Dashboard</td><td>Dashboard</td>";
break;
case "e":
$alertdiv .= "<tr id='selectedmethodtr' value='e$data[3]'>";
$sql1 = "SELECT description, email from page_email where page_email_id=$page_id";
foreach( $db->query($sql1) as $data1 ) {
$alertdiv .= "<td width='50'>E-Mail</td><td>$data1[0]</td><td>$data1[1]</td>";
}
break;
case "p":
$alertdiv .= "<tr id='selectedmethodtr' value='p$data[3]'>";
$sql1 = "SELECT description, phone, carriervalue from page_phone where page_phone_id=$page_id";
foreach( $db->query($sql1) as $data1 ) {
$alertdiv .= "<td width='50' >E-Mail</td><td>$data1[0]</td><td>$data1[1]</td>";
}
break;
}
switch ($completed) {
case "0":
$alertdiv .= "<td>No</td>";
break;
case "1":
$alertdiv .= "<td>Yes</td>";
break;
}
$alertdiv .= "<td>$timestamp</td>";
$alertdiv .= "<td><a onClick=deleteAlert($id) id='deleteAlert'><i class='fa fa-trash-o fa-lg'></i></a></td></tr>";
}
}//end if data[1]
$alertdiv .= "</table>";
echo $alertdiv;
}else {
$alertdiv .= "Alert Type is set Default Dashboard! <br>";
$alertdiv .= "<table id='selectedmethodtable'>";
$alertdiv .= "<tr>";
$alertdiv .= "<td>Description</td>";
$alertdiv .= "<td >Method</td><option id='selectedmethodtr' value='d0' ></option>";
$alertdiv .= "</tr>";
$alertdiv .= "<tr ><td>DashBoard</td><td>Default</td></tr>";
$alertdiv .= "</table>";
echo $alertdiv;
}
}
?>
Your comments ("found results") are wrong.
I'm assuming that $db->query is mysqli's query method.
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
It is a true value if the query ran successfully, even if that query found no matching rows.
You'll get a false result if there was an error running the query.
To test if there are no results, you should use num_rows.
if ($res = $db->query($sql)) { // Query ran without errors
if ($res->num_rows == 0) {
// There were no results found
} else {
while($row = $res->fetch_assoc($result)) {
// Do stuff with the data in the `$row`
}
}
} else {
// There was an error running the query
}
Related
I am trying to convert a mySQL query to PDO.
I have partly got the data coming through as expected but I cannot get the entire query to pull the correct data. The mySQL query is able to pull 4 categories with the appropriate number of entries in each category being pulled and displayed. The PDO conversion query is only pulling 3 categories, and no entries in any category
I am assuming I have not converted the query correctly but I cannot find where the issue is.
I would also like some input on how to limit exposure to SQL injection with the new code.
OLD QUERY (Working)
function listPuppies(){
include("db_connect.php");
$query = " SELECT *
FROM tblLitters
WHERE available = 1
ORDER BY litBreed, litMother";
$resultOut = mysql_query($query, $connection) or die ("<br>Error in query: $query.".mysql_error($connection));
//Check if a row is returned
if (mysql_num_rows($resultOut) > 0) {
while($rowOut = mysql_fetch_array($resultOut)){
$litterID = $rowOut['litterID'];
$litMother = $rowOut['litMother'];
$litBreed = $rowOut['litBreed'];
$litBreedDate = $rowOut['litBreedDate'];
$litDesc = $rowOut['litDesc'];
$litterImage = $rowOut['litImage'];
$litterImageThumb = $rowOut['litterImageThumb'];
$litBreedCost = $rowOut['litBreedCost'];
if ($litterImageThumb == ''){
$litterPic = "";
}else{
$litterPic = "<img src=\"images/Litters/".$litterImageThumb."\" align=\"right\" style=\"padding:1px; margin:3px; border:6px solid #fff;\">";
}
echo "<table width=\"650\"><tr>\n";
if ($breed <> $rowOut['litBreed']){
$breed = $rowOut['litBreed'];
echo "</tr></table>\n";
echo "<br><br><div class=\"breedHead\">$breed's For Sale</div><hr color=\"#C5FBB4\">\n";
echo "<br><table width=\"650\" cellspacing=\"0\" cellpadding=\"5\"><tr><td colspan=\"3\"><table bgcolor=\"#044726\" width=\"100%\" border=\"1\" bordercolor=\"#137b48\" cellpadding=\"6\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Cost: </strong>$$litBreedCost<br><br></span></td></tr></table></td></tr><tr><td colspan=\"3\"> </td></tr>";
$counter = 0;
}else{
if ($pupLitterID <> $rowOut['litterID']){
echo "</table>\n";
echo "<br><br><br><table width=\"650\" cellspacing=\"0\" cellpadding=\"5\"><tr><td colspan=\"3\"><table bgcolor=\"#044726\" width=\"100%\" border=\"1\" bordercolor=\"#137b48\" cellpadding=\"6\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Cost: </strong>$$litBreedCost<br><br></span></td></tr></table></td></tr><tr><td colspan=\"3\"> </td></tr>";
$counter = 0;
}
}
$query = " SELECT *
FROM tblPuppies
WHERE litterID = $litterID";
$result = mysql_query($query, $connection) or die ("<br>Error in query: $query.".mysql_error($connection));
//$breed = $row['pupBreed'];
$counter = 0;
//Check is a row is returned
if (mysql_num_rows($result) > 0) {
//old table start
while($row = mysql_fetch_array($result)){
$status = $row['pupStatus'];
$pupLitterID = $row['litterID'];
if ($status == "For Sale"){
if ($row['pupOnHold'] == 1){
$status = '<font color=\"red\">On Hold</font>';
}
if ($row['pupSold'] == 1){
$status = '<font color=\"red\">Sold</font>';
}
}
if ($row['pupSex'] == 'F'){
$sex = 'Female';
}else{
$sex = 'Male';
}
//used to change popup window position depending on where thumbnail is palced on page
if ($counter == 0){
echo "<td width=\"33%\"><a class=\"thumbnailLeft\" href=\"#thumb\">";
}
if ($counter == 1){
echo "<td width=\"33%\"><a class=\"thumbnail\" href=\"#thumb\">";
}
if ($counter == 2){
echo "<td width=\"33%\"><a class=\"thumbnailRight\" href=\"#thumb\">";
}
echo "<div align=\"center\"><img src=\"images/ForSale/".$row['pupPicThumb']."\" style=\"padding:1px; border:6px solid #fff;\"><br>".$row['pupName']." - $sex<br><strong>$status</strong></div><span><img src=\"images/ForSale/".$row['pupPic']."\"></span></a><div align=\"center\">Contact Us About This Pup</div></td>";
if ($counter == 2){
echo "</tr><tr>\n";
$counter = -1;
if ($breed <> $rowOut['litBreed']){
$breed = $rowOut['litBreed'];
echo "</table>\n";
echo "<br><br><div class=\"breedHead\">$breed's For Sale</div><hr color=\"#C5FBB4\"><br>\n";
echo "<table width=\"95%\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Litter Birth Date: </strong>$litBreedDate<br><br></span></td></tr></table>";
echo "<table width=\"650\"><tr>\n";
$counter = -1;
}
}
$counter = $counter + 1;
}
echo "</tr></table>\n";
}else{
echo "There are no puppies left for sale in this litter, sorry.<br><br>Please check back again soon.";
}// End IF/ELSE
}//end outer while
}else{
echo "There are currently no puppies for sale.<br>Please check back again soon.";
}//end outer if
}
NEW QUERY (Not Working entirely)
function listPuppies(){
include("db_connect.php");
try {
$stmt = $connection->prepare("SELECT * FROM tblLitters WHERE available = 1");
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt->execute();
}
//Catch PDO Query Error
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// set the resulting array to associative
//$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->fetchColumn() > 0) {
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $rowOut){
$litterID = $rowOut['litterID'];
$litMother = $rowOut['litMother'];
$litBreed = $rowOut['litBreed'];
$litBreedDate = $rowOut['litBreedDate'];
$litDesc = $rowOut['litDesc'];
$litterImage = $rowOut['litImage'];
$litterImageThumb = $rowOut['litterImageThumb'];
$litBreedCost = $rowOut['litBreedCost'];
if ($litterImageThumb == ''){
$litterPic = "";
}else{
$litterPic = "<img src=\"images/Litters/".$litterImageThumb."\" align=\"right\" style=\"padding:1px; margin:3px; border:6px solid #fff;\">";
}
echo "<table width=\"600\"><tr>\n";
if ($breed <> $rowOut['litBreed']){
$breed = $rowOut['litBreed'];
echo "</tr></table>\n";
echo "<br><br><div class=\"breedHead\">$breed's For Sale</div><hr color=\"#C5FBB4\">\n";
echo "<br><table width=\"600\" cellspacing=\"0\" cellpadding=\"5\"><tr><td colspan=\"3\"><table bgcolor=\"#044726\" width=\"100%\" border=\"1\" bordercolor=\"#137b48\" cellpadding=\"6\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Cost: </strong>$$litBreedCost<br><br></span></td></tr></table></td></tr><tr><td colspan=\"3\"> </td></tr>";
$counter = 0;
}else{
if ($pupLitterID <> $rowOut['litterID']){
echo "</table>\n";
echo "<br><br><br><table width=\"600\" cellspacing=\"0\" cellpadding=\"5\"><tr><td colspan=\"3\"><table bgcolor=\"#044726\" width=\"100%\" border=\"1\" bordercolor=\"#137b48\" cellpadding=\"6\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Cost: </strong>$$litBreedCost<br><br></span></td></tr></table></td></tr><tr><td colspan=\"3\"> </td></tr>";
$counter = 0;
}
}
$stmt1 = $connection->prepare("SELECT * FROM tblPuppies WHERE litterID = .$litterID.");
$counter = 0;
//Check if a row is returned
if ($stmt1->fetchColumn() > 0) {
//old table start
foreach ($stmt1->fetch(PDO::FETCH_ASSOC) as $rowOut){
$status = $row['pupStatus'];
$pupLitterID = $row['litterID'];
if ($status == "For Sale"){
if ($row['pupOnHold'] == 1){
$status = '<font color=\"red\">On Hold</font>';
}
if ($row['pupSold'] == 1){
$status = '<font color=\"red\">Sold</font>';
}
}
if ($row['pupSex'] == 'F'){
$sex = 'Female';
}else{
$sex = 'Male';
}
//used to change popup window position depending on where thumbnail is placed on page
if ($counter == 0){
echo "<td width=\"33%\"><a class=\"thumbnailLeft\" href=\"#thumb\">";
}
if ($counter == 1){
echo "<td width=\"33%\"><a class=\"thumbnail\" href=\"#thumb\">";
}
if ($counter == 2){
echo "<td width=\"33%\"><a class=\"thumbnailRight\" href=\"#thumb\">";
}
echo "<div align=\"center\"><img src=\"images/ForSale/".$row['pupPicThumb']."\" style=\"padding:1px; border:6px solid #fff;\"><br>".$row['pupName']." - $sex<br><strong>$status</strong></div><span><img src=\"images/ForSale/".$row['pupPic']."\"></span></a><div align=\"center\">Contact Us About This Pup</div></td>";
if ($counter == 2){
echo "</tr><tr>\n";
$counter = -1;
if ($breed <> $rowOut['litBreed']){
$breed = $rowOut['litBreed'];
echo "</table>\n";
echo "<br><br><div class=\"breedHead\">$breed's For Sale</div><hr color=\"#C5FBB4\"><br>\n";
echo "<table width=\"95%\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Litter Birth Date: </strong>$litBreedDate<br><br></span></td></tr></table>";
echo "<table width=\"600\"><tr>\n";
$counter = -1;
}
}
$counter = $counter + 1;
}
echo "</tr></table>\n";
}else{
echo "There are no puppies left for sale in this litter, sorry.<br><br>Please check back again soon.";
}// End IF/ELSE
}//end outer while
}else{
echo "There are currently no puppies for sale.<br>Please check back again soon.";
}//end outer if
}
Thanks in advance
I found my issue for the entries in categories not showing.
Within my query I tried SELECT * WHERE field1 = .$variable.
But I needed to bind the variable as a parameter instead, like so:
$stmt1 = $connection->prepare("SELECT * FROM tblPuppies WHERE litterID = :litterID");
$stmt1->bindParam(':litterID', $litterID);
$stmt1->execute();
This successfully populated my categories as expected.
It is worth noting that Your Common Sense's answer was right, however only answered part of my question. anyone else reading these answers should take note of both answers.
EDIT......
As pointed out by ShowDev, the
' if ($stmt->fetchColumn() > 0)'
condition advanced the count to the second row, and then only returned the remaining 3 records.
The link posted by ShowDev shows correct procedure for this type of query
get rid of if ($stmt->fetchColumn() > 0) condition
for this useless message change to this
$found = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($found) {
foreach ($found as $rowOut){
I have been asked to revise an existing site, it's still using PHP5.3 and an old version of PHPmyDirectory, and the code is a little messy.
I'm trying to revise it to just display the list of cities in two columns. I'm trying to do it as a table, as it seemed easiest, but I could also just pull the results into to side by side divs, as there are never more than 26 cities listed (so first half or first 13 in div one, the rest in div two).
Here's the existing original code (I know its not mysqli, but we'll be redoing this site shortly so there's no sense trying to redo a million pages of code right now):
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
$output = "<p>";
$result_array = array();
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
while ($service2 = fetch_array($result2))
{
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
$output .= "<br/>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
$output .="</p>";
}
}
return $output;
}
This is what is looks like currently: Current Site
Here's what I've tried to do:
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
$result_array = array();
while ($service = fetch_array($result)) {
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
$i=0;
if(!$result2) {
break;
}
else {
while ($service2 = fetch_array($result2)) {
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
$i++;
}
echo "<table>";
for ($j=0; $j<$i; $j=$j+2) {
echo "<tr>";
echo "<td>".$title_array[$j]."</td><td>".$title_array[$j+1]."</td>";
echo "</tr>";
}
echo "</table>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<p><b>".$title." will travel for an additional fee!</b></p>";
}
else {
$output .="";
}
}
return $output;
}
And here's what I'm getting: DEV site
I'm very much a PHP newbie, and my understanding is pretty spotty, but I've tried a bunch of different solutions I've found here, and can't get them to work. I'm sure I'm missing something obvious.
Thanks for any pointers!
if I got it correct you should change your
else {
$output = "<p>";
$result_array = array();
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
while ($service2 = fetch_array($result2))
{
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
$output .= "<br/>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
$output .="</p>";
}
}
with
else {
$output = "<table>";
$result_array = array();
$even_odd=true;
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
$output .= "";
while ($service2 = fetch_array($result2))
{
if ($even_odd) {
$output .= '<tr><td>'."{$service2['title']}".'</td>';
$even_odd=false;
} else {
$output .= '<td>'."{$service2['title']}".'</td></tr>';
$even_odd=true;
}
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
if (!$even_odd)$output .="<td></td></tr>";
$output .="</table>";
}
}
Try this, I couldn't test it of course, since I've got no access to the data being loaded.
echo "<table>";
$result_array = array();
while ($service = fetch_array($result))
{
//this will loop multiple times. 7 times for Tony S. in the example.
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
$i=0;
if(!$result2)
{
break;
}
else
{
while ($service2 = fetch_array($result2))
{
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
$i++;
}
}
}
for ($j=0; $j < count($result_array); $j++)
{
if ($j % 2 == 0)
{
echo "<tr>";
}
echo "<td>".$result_array[$j][0]." (".$result_array[$j][1].")</td>";
if ($j % 2 == 0)
{
echo "</tr>";
}
if ($j % 2 == 1 && $j == count($result_array)-1)
{
echo "<td></td></tr>";
}
}
echo "</table>";
Paste and replace between this lines:
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
.... PASTE IN HERE ....
}
Building on Kim's code, I was able to get it working with some revisions. I also scrapped the table for divs, since it seems less messy to me and it seemed like the table styling was interfering somehow.
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
} else {
$output = "<div>";
//$result_array = array();
$even_odd=true;
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
while ($service2 = fetch_array($result2))
{
if ($even_odd) {
$output .= '<div style="float:left;width:50%;">'."{$service2['title']}".'</div>';
$even_odd=false;
} else {
$output .= '<div style="float:right;width:50%;">'."{$service2['title']}".'</div>';
$even_odd=true;
}
}
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<div style='clear:both;width:90%;float:none;'><p><b>".$title." will travel for an additional fee!</b></p></div>";
} else {
}
}
return $output;
}
Thanks so much Kim and Mouser!
Ive been searching alot lately but couldnt come up for a solution about this problem of looping...
i am currently workin on a page that would display transactions from database and would let you pay using a button.
i made a table and put a button in the last column of every row using while($row = mysql_fetch_array($query)).
i made use of isset that everytime the button is clicked some session will store corresponding to the values of the row...but the problem is whichever button i clicked whether its in the first, second, or third row the values that i get comes from the last row.
Is there a way to get the value of the variables of each row? here are the codes:
$qry1=mysql_query("SELECT * FROM request WHERE client_id ='".$_SESSION['client_id']."'");
$check = mysql_num_rows($qry1);
if ($check == 0) { echo "There are no recent transactions to display."; }
else{
$table = "<table align= 'center' border='1' bordercolor='#ccc' cellpadding='20'>";
$table .= "<tr><th>REQUEST #</th><th>DATE</th><th>TIME</th><th>EVENT</th><th>PRICE</th><th>STATUS</th><th></th></tr>";
while($row = mysql_fetch_array($query)){
print_r($row);
$rid = $row['request_id'];
$reid = $row['event_id'];
$raid = $row['addons_id'];
$reprice = $row['request_price'];
$redate = $row['event_date'];
$retime = $row['event_time'];
$restatus = $row['event_status'];
if($reid==1 || $reid==2 || $reid==3){
$debut="Standard Debut";
}
else { $debut="Kids Party";
}
$table .= "<tr><td align = center># ".$rid."</td><td>".$redate."</td><td>".$retime."</td><td align= center>".$debut."</td><td align=center>P".$reprice.".00</td><td align=center>".$restatus."</td>";
if($restatus=='PENDING')
{
$table .= "<td align=center>";
$table .= "<form method='post'>";
$table .= "<input type='submit' name='btnSubmit' id='btnSubmit' value='Pay' tabindex='0' />
</form>
</td>";
include "../pages/my_reqsubmit.php";
}
else
{
$table .= "<td align=center>--</td>";
}
$table .= "</tr>";
}
$table .= "</table>";
echo $table;
code for my_reqsubmit.php :
if(isset($_POST["btnSubmit"]))
{
include("../pages/config.php");
$URL= "../request/view.php";
$_SESSION['RequestUser']="asd";
$_SESSION['dtRequest'] = $redate;
$_SESSION['tmRequest'] = $retime;
$_SESSION['etype'] = $debut;
$_SESSION['addons_id'] = $raid;
if($reid==1){
$_SESSION['epack']= "Package A";
}
else if($reid==2){
$_SESSION['epack']= "Package B";
}
else if($reid==3){
$_SESSION['epack']= "Package C";
}
else if($reid==4){
$_SESSION['epack']= "Package A";
}
else if($reid==5){
$_SESSION['epack']= "Package B";
}
else if($reid==6){
$_SESSION['epack']= "Package C";
}
$qrry2 = mysql_query("SELECT * FROM addons WHERE addons_id =$raid");
while($row = mysql_fetch_array($qrry2)){
$_SESSION['pservice'] = $row['addons_ps'];
$_SESSION['pbooth'] = $row['addons_pb'];
$_SESSION['mbar'] = $row['addons_mb'];
$_SESSION['phprice'] = 3500;
$_SESSION['pbprice'] = 5000;
$_SESSION['mbprice'] = 11000;
}
$qrry3 = mysql_query("SELECT * FROM event WHERE event_id =$reid");
while($row = mysql_fetch_array($qrry3)){
$_SESSION['eprice'] = $row['event_price'];
}
$_SESSION['price'] = $reprice;
header ("Location: $URL");
}
?>
Please help me...id really appreciate it!
You need to include SOMETHING in your button to link that row's button with the matching DB record. I'll use <a> tags instead, but the EXACT same concept is used for buttons:
Click here for record #1
^---the ID of the record that this button/link would use
Click here for record #2
Click here for record #3
I am trying to delete a user from my simple E-commerce website for a project I am working on. When I click the delete button, the message appears and tells me that it correctly deleted the data from the table. But when I go into my sql database and check the data, its all still there. I cant figure out what I am doing wrong or where my error is. any help would be appreciated. My code is below.
<?php
session_start();
if (isset($_SESSION['shirt_users_id']) && isset($_SESSION['full_name'])) {
require('mysql_connect.php');
$title="List all registered users";
include_once("header_admin.php");
if (isset($_GET['shirt_users_id'])) {
$shirt_users_id = $_GET['shirt_users_id'];
function rollback_die($msg)
{
echo $msg;
global $link;
mysqli_query($link, "ROLLBACK");
mysqli_free_result($exec_select_sui);
mysqli_close($link);
include("footer_admin.php");
die();
}
function delete_records($array_refer)
{
global $link;
foreach ($array_refer as $key => $array_value) {
$table_name = substr($key, 0, -3);
foreach ($array_value as $value) {
$delete = "DELETE from $table_name where $key = $value";
$exec_delete = #mysqli_query($link, $delete);
if (!$exec_delete) {
rollback_die("Records from $table_name could not be deleted because of: ".mysqli_error($link));
}
}
}
return true;
}
#mysqli_query($link, "SET AUTOCOMMIT=0");
$select_sui = "SELECT shirt_users.shirt_users_id, shirt_users_types.shirt_users_types_id, shirt_orders.shirt_orders_id, shirt_shipping_addresses.shirt_shipping_addresses_id, shirt_billing_addresses.shirt_billing_addresses_id, shirt_credit_cards.shirt_credit_cards_id
from
shirt_users, shirt_users_types, shirt_orders, shirt_shipping_addresses, shirt_billing_addresses, shirt_credit_cards
where
shirt_users.shirt_users_id = shirt_users_types.shirt_users_id and
shirt_users_types.shirt_orders_id = shirt_orders.shirt_orders_id and
shirt_orders.shirt_shipping_addresses_id = shirt_shipping_addresses.shirt_shipping_addresses_id and
shirt_orders.shirt_billing_addresses_id = shirt_billing_addresses.shirt_billing_addresses_id and
shirt_orders.shirt_credit_cards_id = shirt_credit_cards.shirt_credit_cards_id and
shirt_users.shirt_users_id = $shirt_users_id";
$exec_select_sui = #mysqli_query($link, $select_sui);
if (!$exec_select_sui) {
rollback_die("A problem when retrieving records from the database for shirt user has occurred: ".mysqli_error($link));
} else {
$users = $gut = $orders = $shipping = $billing = $credit = array();
while ($one_row = mysqli_fetch_assoc($exec_select_sui)) {
$users[] = $one_row['shirt_users_id'];
$gut[] = $one_row['shirt_users_types_id'];
$orders[] = $one_row['shirt_orders_id'];
$shipping[] = $one_row['shirt_shipping_addresses_id'];
$billing[] = $one_row['shirt_billing_addresses_id'];
$credit[] = $one_row['shirt_credit_cards_id'];
}
$multi_array = array('shirt_users_id' => $users, 'shirt_users_types_id' => $gut, 'shirt_orders_id' => $orders, 'shirt_shipping_addresses_id' => $shipping, 'shirt_billing_addresses_id' => $billing, 'shirt_credit_cards_id' => $credit);
delete_records($multi_array);
echo "the record(s) of shirt user have successfully been deleted from the tables";
mysqli_query($link, "COMMIT");
}
}
(isset($_GET['sort']))?$sort = $_GET['sort']:$sort = 'ui';
(isset($_GET['bool']))?$bool = $_GET['bool']:$bool=true;
switch ($sort) {
case 'ui': ($bool)?$sort = "user_id ASC":$sort = "user_id DESC";
break;
case 'fn': ($bool)?$sort = "first_name ASC":$sort = "first_name DESC";
break;
case 'ln': ($bool)?$sort = "last_name ASC":$sort = "last_name DESC";
break;
case 'em': ($bool)?$sort = "email ASC":$sort = "email DESC";
break;
}
$select_users = "SELECT shirt_users_id, user_id, first_name, last_name, email from shirt_users order by $sort";
$exec_select_users = #mysqli_query($link, $select_users);
if (!$exec_select_users) {
echo "The user information could not be retrieved from the shirt_users table because of: ".mysqli_error($link);
mysqli_close($link);
include('footer_admin.php');
die();
} else {
echo "<div id='list_users'><table id='list_user' border='0'>";
echo "<tr>";
echo "<th><a href='".$_SERVER['PHP_SELF']."?sort=ui&bool=".!$bool."'>User ID</a></th>";
echo "<th><a href='".$_SERVER['PHP_SELF']."?sort=fn&bool=".!$bool."'>First Name</a></th>";
echo "<th><a href='".$_SERVER['PHP_SELF']."?sort=ln&bool=".!$bool."'>Last Name</a></th>";
echo "<th><a href='".$_SERVER['PHP_SELF']."?sort=em&bool=".!$bool."'>Email</a></th>";
echo "<th>Delete</th>";
echo "</tr>";
while ($one_row = mysqli_fetch_assoc($exec_select_users)) {
echo "<tr>";
echo "<td class='first'>".$one_row['user_id']."</td>";
echo "<td class='second'>".$one_row['first_name']."</td>";
echo "<td class='third'>".$one_row['last_name']."</td>";
echo "<td class='fourth'>".$one_row['email']."</td>";
echo "<td class='fifth'><a href='".$_SERVER['PHP_SELF']."?shirt_users_id=".$one_row['shirt_users_id']."'>Delete</a></td>";
echo "</tr>";
}
echo "<tr><td colspan = '4' class='footer'>Total number of users: </td><td class='footer'>".mysqli_num_rows($exec_select_users)."</td></tr>";
echo "</table></div>";
}
mysqli_free_result($exec_select_users);
} else {
echo "You are not an authentic administrator. Being directed to the login page...";
header("Refresh: 2; url='login.php'");
}
mysqli_close($link);
include("footer.php");
die();
?>
Also, I know my code is not the most efficient way to do things but im new to the whole html/css/php scene and am trying my best so please dont give me some off the wall answer about a differnt way to do this please!
I have a html form tat my user can use to search through a table in my MYSQL database.
By default if you just hit go it will display the entire table, however I would like them to be able select certain fields and my php form to search via the fields that are filled in.
I seem to be unable to find a way of doing this without writing a seperate query for all 11 inputs in the different combinations they could be entered in, which comes out at a total of 76 queries..
If anyone has a way to simplify this I would love any advice.
I have tried just running a query with the AND operator but that doesnt work as some variables can be left empty and that will return no result, not sure if that is what is upposed to happen, but that is what is happening.
my html and php:
http://jsbin.com/oquwid/1/edit
PHP
$sql = "SELECT * FROM ".$tbl_name."
WHERE fname='".$fname."'
and lname='".$lname."'
and city='".$city."'
and phone='".$pohne."'
and interest_inet='".$internet."'
and interest_tv='".$television."'
and interest_voice='".$voice."'
and submission_ip='".$ip."'
and inquiry_handled='".$handled."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
echo $row;
}
echo "</table>";
You could append parts to the query depending on which are filled in:
if(!empty($fname) || !empty($lname) || !empty($city) || etc.etc.) {
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryParts = array();
if($fname != "") {
$queryParts[] = " fname='$fname'";
}
if($lname != "") {
$queryParts[] = " lname='$lname'";
}
etc.etc.
$sql .= implode(" AND ", $queryParts);
// do query, etc.
}
else {
// Don't do query if no parameters are specified
}
You also need to make sure that you escape all of your query parameters before you use them or risk having someone ravage your data.
The following uses loops to avoid duplicate code:
$fieldIsSpecified = false;
$queryFields = array('fname' => $fname, 'lname' => $lname, 'city' => $city, etc...);
foreach($queryFields as $column => $value) {
if(!empty($value){
$fieldIsSpecified = true;
break;
}
}
if($fieldIsSpecified) {
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryParts = array();
foreach($queryFields as $column => $value) {
if(!empty($value)) {
$queryParts[] = " $column = '$value'";
}
}
$sql .= implode(" AND ", $queryParts);
// do query, etc.
}
else {
// Don't do query if no parameters are specified
}
The reason you're query isn't working if a value is not filled in, is probably because the query results in this (given first name is empty)
SELECT * FROM $tbl_name WHERE fname=''
And there probably isn't a user having no first name.
Further, you considered adding a flag per requested info, and on base of that either add or remove the needed part to the select part of the query ?
For example,
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryChanged = false;
if (isset($fname)){
if (!empty($fname)){
$sql .= "fname='$fname' ";
$queryChanged=true;
}
}
if (isset($lname)){
if (!empty($lname)){
$sql .= ($queryChanged) ? " AND lname='$lname'" : "lname='$lname'";
$queryChanged = true;
}
}
... //Continue the logic
I'd recommend you to read this post about select * as well as this about user input and how to handle it
this is how i am going to have to do it
php:`
//if just lname is set
if(empty($start_date) && empty($end_date) && empty($fname) && isset($lname) && empty($city) &&
empty($internet) && empty($television) && empty($voice) && empty($phone) && empty($ip) &&
empty($handled) && empty($not_handled)){
$sql = "SELECT * FROM ".$tbl_name."
WHERE lname='".$lname."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
}
echo "</table>";
exit();
}
//if just city is selected
if(empty($start_date) && empty($end_date) && empty($fname) && empty($lname) && isset($city) &&
empty($internet) && empty($television) && empty($voice) && empty($phone) && empty($ip) &&
empty($handled) && empty($not_handled)){
$sql = "SELECT * FROM ".$tbl_name."
WHERE city='".$city."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
}
echo "</table>";
exit();
}
And etc... i am going to have to repeat this process until i cover all, 76 i believe, possibilites. thnkfully its just a lot of copy paste. thanks for the help everyone
First don't use MYSQL_*. Use PDO
Second, with your code, your are requiring all fields to be filled.
If you don't wanna do that then go this way:
You can use WHERE 1=1 , but it's not recommended !!!!!
$sql = "SELECT * FROM ".$tbl_name." WHERE confirm = '0' ";
$sql .= "AND fname = ".$fname."";
$sql .= "AND lname = ".$lname."";
$sql .= "AND city = ".$city."";
$sql .= "AND phone = ".$pohne."";
$sql .= "ORDER BY date DESC";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
echo $row;
}
echo "</table>";