I tried to show some data from database with select option from the first page
but I got two error when the page tried to retrieve the data from database
the errors are
mysql_num_rows() expects parameter 1 to be resource, boolean given
and
mysql_fetch_array() expects parameter 1 to be resource, boolean given
this is my code
<?php
//connect to server
$connect = mysql_connect("localhost", "root", "");
//connect to database
//select the database
mysql_select_db("fak_databases");
//submit button
if($_POST['formSubmit'] == "Submit")
{
$country = $_POST['country'];
}
//query the database
if($country == TRUE) {
$order = "";
$sort = "asc";
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 WHERE applicant1_country='$country' FROM auip_wipo_sample";
if(isset($_GET['orderby'])){
$order = $_GET['orderby'];
$sort = $_GET['sort'];
//limiting the possible values of order/sort variables
if($order != 'wipo_applicant1_city' && $order != 'applicant1_addr1')$order = "applicant1_addr1";
if($sort != 'asc' && $sort != 'desc')$sort = "asc";
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE applicant1_country='$country' ORDER BY ".mysql_real_escape_string($order)." ".$sort;
//here we reverse the sort variable
if($sort == "asc"){
$sort = "desc";
}
else{
$sort = "asc";
}
}
}
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$row_counter = 0;
$icon = "";
echo "<table border=\"1\" cellspacing=\"0\">\n";
echo "<tr>\n";
// first column
echo "<th>";
$icon = "";
if($order == "wipo_applicant1_city"){
if($sort == "asc"){
$icon = "<img src=\"images/up.png\" class=\"arrowSpace\"/>";
}
if($sort == "desc"){
$icon = "<img src=\"images/down.png\" class=\"arrowSpace\"/>";
}
}
//print the result
echo "<a href='index.php?orderby=wipo_applicant1_city&sort=".$sort."'>City</a>".$icon;
echo "</th>\n";
// second column
echo "<th>";
$icon = "";
if($order == "applicant1_addr1"){
if($sort == "asc"){
$icon = "<img src=\"images/up.png\" class=\"arrowSpace\"/>";
}
if($sort == "desc"){
$icon = "<img src=\"images/down.png\" class=\"arrowSpace\"/>";
}
}
echo "<a href='index.php?orderby=applicant1_addr1&sort=".$sort."'>Address</a>".$icon;
echo "</th>\n";
echo "</tr>";
//fetch the result
while($row = mysql_fetch_array($result))
{
if($row_counter % 2){
$row_color="bgcolor='#FFFFFF'";
}else{
$row_color="bgcolor='#F3F6F8'";
}
echo "<tr class=\"TrColor\" ".$row_color.">";
echo "<td>" . $row['wipo_applicant1_city'] . "</td>\n";
echo "<td>" . $row['applicant1_addr1'] . "</td>\n";
echo "</tr>";
$row_counter++;
}
Print "</table>";
?>
the line got error are
$num_rows = mysql_num_rows($result);
and
while($row = mysql_fetch_array($result))
I think I already gave parameter in this line
$result = mysql_query($sql);
anyone know how to fix this?
thanks
try this
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE
applicant1_country='".$country."'";
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){
Edited, please scroll down
I am trying to display 3 variables which consist of data stored in a SQL database. However, only the first gets echoed successfully (topLeftUrl). It is worth noting that the same PHP file also receives data from an input (also in the same PHP file) and stores it in the same SQL database. This code was written for testing purposes and may not be entirely safe.
//Connect
$con = mysqli_connect ("localhost","noneedtoknow","noneedtoknow","noneedtoknow");
if (mysqli_connect_errno())
{
echo "Error: ", mysql_connect_error(), "<br>";
die ();
}
//Store input in SQL database
$result = mysqli_query ($con, "SELECT * FROM edit");
$message = stripslashes ($_POST ['message']);
if ($message !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$message' WHERE id='message'"); }
$topLeftNew = ($_POST ['topLeftUrl']);
if ($topLeftNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topLeftNew' WHERE id='topLeft'"); }
$topRightNew = ($_POST ['topRightUrl']);
if ($topRightNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topRightNew' WHERE id='topRight'"); }
//First echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topLeft" && $done2 == 0)
{
$topLeftUrl = $row["cont"];
}
}
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
//Second echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topRight" && $done3 == 0)
{
$topRightUrl = $row["cont"];
}
}
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
//Third echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "message" && $done == 0)
{
echo $row["cont"];
}
}
Edit:
I updated the code, and the problem seems to have changed. For some reason, echo $messageCont; displays an old value of cont WHERE id='message'. The database itself is updated successfully, though, and I see the new value of cont once I refresh the page/re-submit the form. Why do I not see the current value of cont immediately after form submission, though? Here is the new code:
/* Before <!DOCTYPE html> */
//Connect
$con = mysqli_connect ("localhost","noneedtoknow","noneedtoknow","noneedtoknow");
if (mysqli_connect_errno())
{
echo "Error: ", mysql_connect_error(), "<br>";
die ();
}
//Query and update
$result = mysqli_query ($con, "SELECT * FROM edit");
$message = stripslashes ($_POST ['message']);
if ($message !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$message' WHERE id='message'"); }
$topLeftNew = ($_POST ['topLeftUrl']);
if ($topLeftNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topLeftNew' WHERE id='topLeft'"); }
$topRightNew = ($_POST ['topRightUrl']);
if ($topRightNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topRightNew' WHERE id='topRight'"); }
//Query again and read
$done0 = 0;
$done1 = 0;
$done2 = 0;
mysqli_data_seek ($result, 0);
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topLeft" && $done0 == 0)
{
$topLeftUrl = $row["cont"];
$done0 = 1;
}
else if ($row["id"] == "topRight" && $done1 == 0)
{
$topRightUrl = $row["cont"];
$done1 = 1;
}
else if ($row["id"] == "message" && $done2 == 0)
{
$messageCont = $row["cont"];
$done2 = 1;
}
else null;
}
/* After <!DOCTYPE html> */
/* Form code was omitted as it works perfectly. It is in this same file, though. */
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
echo $messageCont;
Any help is appreciated.
Edit: I only had to replace mysqli_data_seek () with the line beginning by $result (cut/paste). Thank you.
I ran into this same problem on my site....you run multiple mysql_fetch_array() on the same query ($result)...I thought this would work on my site but this failed for all but the first of 6 while loops which all referenced the same query on my site (I'm sorry but I don't remember the exact error message in my error_log). Try condensing your 3 while loops into 1 loop, something like this:
while ($row = mysqli_fetch_array ($result)) {
if ($row["id"] == "topLeft" && $done2 == 0) {
$topLeftUrl = $row["cont"];
} else if ($row["id"] == "topRight" && $done3 == 0) {
$topRightUrl = $row["cont"];
} else if ($row["id"] == "message" && $done == 0) {
echo $row["cont"];
} else null;
}
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
I tried to sort the particular data from my database. I have done to show the particular data according to the user input from the first page. However when I tried to sort the table, I got some errors which are undefined variable
this is my code to show the data in table and sort the table
<?php
//connect to server
$connect = mysql_connect("localhost", "root", "") or die('no database');
//connect to database
//select the database
mysql_select_db("fak_databases");
//submit button
if($_POST['formSubmit'] == "Submit")
{
$country = $_POST['country'];
}
//query the database
if($country == TRUE) {
$order = "";
$sort = "asc";
if(isset($_GET['orderby'])){
$order = $_GET['orderby'];
$sort = $_GET['sort'];
//limiting the possible values of order/sort variables
if($order != 'wipo_applicant1_city' && $order != 'applicant1_addr1')$order = "applicant1_addr1";
if($sort != 'asc' && $sort != 'desc')$sort = "asc";
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE applicant1_country='$country' ORDER BY ".mysql_real_escape_string($order)." ".$sort;
//here we reverse the sort variable
if($sort == "asc"){
$sort = "desc";
}
else{
$sort = "asc";
}
}
}
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE applicant1_country='$country'";
$result = mysql_query($sql) or die('failed to run');
$num_rows = mysql_num_rows($result);
$row_counter = 0;
$icon = "";
echo "<table border=\"1\" cellspacing=\"0\">\n";
echo "<tr>\n";
// first column
echo "<th>";
$icon = "";
if($order == "wipo_applicant1_city"){
if($sort == "asc"){
$icon = "<img src=\"images/up.png\" class=\"arrowSpace\"/>";
}
if($sort == "desc"){
$icon = "<img src=\"images/down.png\" class=\"arrowSpace\"/>";
}
}
//print the result
echo "<a href='showDB1.php?orderby=wipo_applicant1_city&sort=".$sort."'>City</a>".$icon;
echo "</th>\n";
// second column
echo "<th>";
$icon = "";
if($order == "applicant1_addr1"){
if($sort == "asc"){
$icon = "<img src=\"images/up.png\" class=\"arrowSpace\"/>";
}
if($sort == "desc"){
$icon = "<img src=\"images/down.png\" class=\"arrowSpace\"/>";
}
}
echo "<a href='showDB1.php?orderby=applicant1_addr1&sort=".$sort."'>Address</a>".$icon;
echo "</th>\n";
echo "</tr>";
//fetch the result
while($row = mysql_fetch_array($result))
{
if($row_counter % 2){
$row_color="bgcolor='#FFFFFF'";
}else{
$row_color="bgcolor='#F3F6F8'";
}
echo "<tr class=\"TrColor\" ".$row_color.">";
echo "<td>" . $row['wipo_applicant1_city'] . "</td>\n";
echo "<td>" . $row['applicant1_addr1'] . "</td>\n";
echo "</tr>";
$row_counter++;
}
Print "</table>";
?>
I got errors on
Undefined index: formSubmit in C:\xampp\htdocs\fak_ict1999\sorting\showDB1.php
Undefined variable: country in C:\xampp\htdocs\fak_ict1999\sorting\showDB1.php
Undefined variable: country in C:\xampp\htdocs\fak_ict1999\sorting\showDB1.php
Undefined variable: order in C:\xampp\htdocs\fak_ict1999\sorting\showDB1.php
Undefined variable: sort in C:\xampp\htdocs\fak_ict1999\sorting\showDB1.php
and when I analyze my code I think I got a logic error on the
if($_POST['formSubmit'] == "Submit")
{
$country = $_POST['country'];
}
//query the database
if($country == TRUE) {
$order = "";
$sort = "asc";
if(isset($_GET['orderby'])){
$order = $_GET['orderby'];
$sort = $_GET['sort'];
//limiting the possible values of order/sort variables
if($order != 'wipo_applicant1_city' && $order != 'applicant1_addr1')$order = "applicant1_addr1";
if($sort != 'asc' && $sort != 'desc')$sort = "asc";
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE applicant1_country='$country' ORDER BY ".mysql_real_escape_string($order)." ".$sort;
//here we reverse the sort variable
if($sort == "asc"){
$sort = "desc";
}
else{
$sort = "asc";
}
}
}
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE applicant1_country='$country'";
because when I tried to to sort the table, the sorting function is trying to access the formsubmit again which is the the form submit is only accessed on the first page when the user choose their option.
is anyone know how to solve this?
my html code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Data Mining</title>
</head>
<body>
<form action="showDB.php" method="post">
<table border="0">
<tr>
<th colspan="3">test</th>
</tr>
<tr>
<td>Select Foreign Agent Country</td>
<td></td>
<td>
<select name="country">
<option value="US">United States</option>
<option value="NZ">New Zealand</option>
<option value="JP">Japan</option>
</select>
</td>
</tr>
<td colspan="3">
<input type="submit" name="formSubmit" value="Submit">
</td>
</table>
</form>
</body>
</html>
here is my javascript code
function SelectAll(btn) {
var blnVal = false;
if (btn.value == "Select All") {
btn.value = "Unselect All";
blnVal = true;
}else {
btn.value = "Select All";
blnVal = false;
}
var d = document.forms["auip_wipo_sample"];
if(d["auip_wipo_sample[]"] == null)
{}
else if (d["auip_wipo_sample[]"].length == null) {
d["auip_wipo_sample[]"].checked = blnVal;
}
else {
for (var i = 0; i < d["auip_wipo_sample[]"].length; i++) {
d["auip_wipo_sample[]"][i].checked = blnVal;
}
}
}
The problem for your variables is that you forgot to initialize $country and that you need to check with e.g. isset() or empty() if the $_POST global value "formSubmit" is available.
Example code here:
<?php
print_r($_POST);
$country = '';
if (isset($_POST['submitted']) && $_POST['submitted'] === 'submit')
{
$country = 'Pangea';
}
print $country;
if ($country == true)
{
print ' => country is true' . PHP_EOL;
}
else
{
print ' => country is false' . PHP_EOL;
}
?>
<!doctype html>
<html>
<head>
</head>
<body>
<form id="myForm" action="test.php" method="post">
<input type="submit" name="submitted" value="submit" />
</form>
</body>
</html>
Hope this helps you.
Going through your code I see somethings that I've tried to explain why they don't work:
Then of course you should not use mysql_* functions because they're deprecated. I don't understand where your call is to the js function, so I left that part out for now.
I hope this is of some help.
<?php
//connect to server
$connect = mysql_connect("localhost", "root", "") or die('no database');
//connect to database
//select the database
mysql_select_db("fak_databases");
//submit button
/* skip this part. Only relevant to check name of submit button when having more submit-buttons in same form
if($_POST['formSubmit'] == "Submit")
{
$country = $_POST['country'];
}
*/
//query the database
//if($country == TRUE) {
if (isset($_REQUEST['country']) { //do like this instead (because country can arrive from link or from form
$country = $_REQUEST['country'];
$order = "";
$sort = "asc";
//if(isset($_GET['orderby'])){ change to:
if(isset($_GET['orderby']) && isset($_GET['sort'])) {
$order = $_GET['orderby'];
$sort = $_GET['sort']; //You're getting the value from $_GET['sort'] but you never check if it is set (like you do with orderby)
//limiting the possible values of order/sort variables
if($order != 'wipo_applicant1_city' && $order != 'applicant1_addr1')$order = "applicant1_addr1";
if($sort != 'asc' && $sort != 'desc')$sort = "asc";
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE applicant1_country='$country' ORDER BY ".mysql_real_escape_string($order)." ".$sort;
//here we reverse the sort variable
if($sort == "asc"){
$sort = "desc";
}
else{
$sort = "asc";
}
}
//} End of check isset($_GET['country']) should be move down to assure that $country is set
$sql = "SELECT wipo_applicant1_city, applicant1_addr1 FROM auip_wipo_sample WHERE applicant1_country='$country'";
$result = mysql_query($sql) or die('failed to run');
$num_rows = mysql_num_rows($result);
$row_counter = 0;
$icon = "";
echo "<table border=\"1\" cellspacing=\"0\">\n";
echo "<tr>\n";
// first column
echo "<th>";
$icon = "";
if($order == "wipo_applicant1_city"){
if($sort == "asc"){
$icon = "<img src=\"images/up.png\" class=\"arrowSpace\"/>";
}
if($sort == "desc"){
$icon = "<img src=\"images/down.png\" class=\"arrowSpace\"/>";
}
}
//print the result
//echo "<a href='showDB1.php?orderby=wipo_applicant1_city&sort=".$sort."'>City</a>".$icon; //orderby and sort is defined but not $_POST['country']
echo "<a href='showDB1.php?country=".$country."&orderby=wipo_applicant1_city&sort=".$sort."'>City</a>".$icon; //change to this instead so country is passed
echo "</th>\n";
// second column
echo "<th>";
$icon = "";
if($order == "applicant1_addr1"){
if($sort == "asc"){
$icon = "<img src=\"images/up.png\" class=\"arrowSpace\"/>";
}
if($sort == "desc"){
$icon = "<img src=\"images/down.png\" class=\"arrowSpace\"/>";
}
}
//echo "<a href='showDB1.php?orderby=applicant1_addr1&sort=".$sort."'>Address</a>".$icon; //orderby and sort is defined but not $_POST['country']
echo "<a href='showDB1.php?country=".$country."&orderby=applicant1_addr1&sort=".$sort."'>Address</a>".$icon; //change to this instead so country is passed
echo "</th>\n";
echo "</tr>";
//fetch the result
while($row = mysql_fetch_array($result))
{
if($row_counter % 2){
$row_color="bgcolor='#FFFFFF'";
}else{
$row_color="bgcolor='#F3F6F8'";
}
echo "<tr class=\"TrColor\" ".$row_color.">";
echo "<td>" . $row['wipo_applicant1_city'] . "</td>\n";
echo "<td>" . $row['applicant1_addr1'] . "</td>\n";
echo "</tr>";
$row_counter++;
}
Print "</table>";
} //End of check isset($_GET['country']) is moved to the end
?>
I'm trying to read a .CSV file and print it in a table format in HTML. At the end of the page is a comments text field where comments get submitted and saved in the database.
When I tested the code below locally it works fine. When I tried to run it on the linux server, it prints out fine when first opened, but when I press submit to save a comment, the page refreshes and the table does not print. Giving an "Invalid argument supplied for foreach()" error. (Note: this doesn't happen locally, i can submit all I want and it does not return an error.)
I've searched on stackoverflow and it seems that most of these problems are related to declaring the variable as an array. However, it seems odd to me as the code works fine the first time with no error, but once I submit it returns an error.
UPDATE: full code for file posted below.
<script>
window.onunload = refreshParent;
function refreshParent() {
window.opener.location.reload();
}
</script>
<?php
//---------------------------------Head/BG---------------------------------------
//Request Case ID
$case = "";
if(isset($_REQUEST['case'])) {
$case = $_REQUEST['case'];
}
$patientID = "";
if(isset($_REQUEST['patient'])) {
$patientID = $_REQUEST['patient'];
}
//Include basic functions to allow connection to SQL db.
include("generic.php");
//Include css and header information.
$printTitle = "Volume Report for Case ".$case."";
$printHeader = "Volume Report for Case ".$case."";
$printFooter = "";
$printBreadcrumb = "";
include("header.php");
//submit tableStatus update
if(isset($_REQUEST['submit'])) {
saveTableStatus($case);
}
//-----------------------------Start of Content----------------------------------
showStatusComment($case);
printVolumeTable($case,$patientID);
tableStatus($case);
//---------------------------End of Content--------------------------------------
//---------------------------Functions Definitions-------------------------------
//print report.csv Table
function printVolumeTable($case,$patientID){
echo "<html><body><table border='1'>\n\n";
$f = fopen("analyze/".$case."/".$patientID."/report.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "<tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
}
function showStatusComment($case) {
$connection = getMySqlConnection();
$sql = "SELECT p.STATUS_NAME, c.volume_comments FROM cases c, primary_status_lookup as p WHERE c.volume_status=p.STATUS_ID and c.caseid='".$case."'";
$result = mysql_query($sql, $connection) or die(mysql_error());
if($result!== FALSE){
while ($record = mysql_fetch_row($result)) {
$status=$record[0];
$comments=$record[1];
if($status == 'Clear Status') {$status = 'None'; $comments = 'None';}
print("<p><b>Table Status: </b>".$status." / <b>Comments: </b>".$comments."</p>");
}
}
}
//Status & Comments
function tableStatus($case) {
$connection = getMySqlConnection();
$sql = "SELECT volume_status, volume_comments FROM cases WHERE caseid='".$case."'";
$result = mysql_query($sql, $connection) or die(mysql_error());
if($result!== FALSE){
while ($record = mysql_fetch_row($result)) {
$status=$record[0];
$comments=$record[1];
print("<form><p>");
showStatusComment($case);
statusDropdown($case,$status);
print("<input type=hidden name='case' value='".$case."'/>");
print(" <label><b>Comments:</b><textarea name='comments' cols=70 rows=2 >".$comments."</textarea></label><br/><br/>");
print("<input type='submit' name='submit' value='Submit'/><INPUT type='button' value='Close Window' onClick='window.close()'></form>");
}
}
}
//Status Dropdown
function statusDropdown($case,$status){
print("<b>Status:</b>");
$dropdown = "<select name = 'status'><option selected='selected' value=NULL>--Select Status--</option>";
$connection = getMySqlConnection();
$sql = "SELECT STATUS_ID, STATUS_NAME FROM primary_status_lookup ORDER BY STATUS_ID ASC";
$result = mysql_query($sql, $connection) or die(mysql_error());
while($record=mysql_fetch_array($result)){
if ($status == '') {
$dropdown .= "<option value = '{$record['STATUS_ID']}'> {$record['STATUS_NAME']}</option>";
} else if (($status == $record['STATUS_ID']) && ($status == '99')) {
$dropdown .= "<option value = '{$record['STATUS_ID']}'> {$record['STATUS_NAME']}</option>";
} else if ($status == $record['STATUS_ID']) {
$dropdown .= "<option value = '{$record['STATUS_ID']}' selected='selected'> {$record['STATUS_NAME']}</option>";
} else {
$dropdown .= "<option value = '{$record['STATUS_ID']}'> {$record['STATUS_NAME']}</option>";
}
}
$dropdown .="</select>";
echo $dropdown;
}
function saveTableStatus($case)
{
//retrieve selected status
$status = '';
if(isset($_REQUEST['status'])) {
$status = $_REQUEST['status'];
}
//retrieve typed comments
if(isset($_REQUEST['comments'])) {
$comments = $_REQUEST['comments'];
}
if($status=='NULL') {
print("<p class='error'>No status selected, please select a status and try again.</p>");
}
else if (($status!=='NULL')){
$connection = getMySqlConnection();
mysql_query("START TRANSACTION", $connection);
if ($status =='99') {$comments = '';}
$result= mysql_query("Update cases Set volume_status=".$status.", volume_comments ='".mysql_real_escape_string($comments)."' Where caseid='".mysql_real_escape_string($case)."'", $connection);
if($result) {
mysql_query("COMMIT", $connection);
print("<p class='saved'>Table Status Updated!</p>");
} else {
mysql_query("ROLLBACK", $connection);
}
mysql_close($connection);
}
}
?>
If you form, and the script that takes the posted form are not on the same path, then your
$f = fopen("analyze/".$case."/".$patientID."/report.csv", "r");
will not open the same file.
Edit -
Okay I think your problem is your $case variable. If there is no request, the $case is blank (""). So the above line will open "analyze///report.csv" As you can see depending on this code
$case = "";
if(isset($_REQUEST['case'])) {
$case = $_REQUEST['case'];
}
Can someone help me on this. I'm made an image uploader and i want the image to make another tr if it reach to 5 pics so it will not overflow. Here is my code:
$dbc = mysql_connect("localhost" , "root" , "") or die (mysql_error());
mysql_select_db('blog_data') or die (mysql_error());
$sql = "SELECT * FROM img_uploaded";
$result = mysql_query($sql);
while($rows=mysql_fetch_array($result))
{
if ($rows)
{
echo "<tr><td><img src='user_images/".$rows['img_name'] . "' width='100' height='100'></td></tr>";
}
else
{
echo "<td><img src='user_images/".$rows['img_name'] . "' width='100' height='100'></td>";
}
}
mysql_close();
E.g. by using the modulus operator:
$dbc = mysql_connect("localhost" , "root" , "") or die (mysql_error());
mysql_select_db('blog_data', $dbc) or die (mysql_error($dbc));
$sql = "SELECT * FROM img_uploaded";
$result = mysql_query($sql, $dbc) or die(mysql_error($dbc));
echo '<table><tr><th>image</th>';
for($cnt=0; false!==($row=mysql_fetch_array($result)); $cnt++) {
if ( 0===$cnt%5 ) {
echo '</tr><tr>';
}
echo '<td><img src="user_images/'.$rows['img_name'] . '" width="100" height="100"></td>';
}
echo '</tr></table>';
It uses the modulus operator, but in addition it checks that a has been opened.
$dbc = mysql_connect("localhost" , "root" , "") or die (mysql_error());
mysql_select_db('blog_data') or die (mysql_error());
$sql = "SELECT * FROM img_uploaded";
$result = mysql_query($sql);
$numOfRows = 0;
while($rows = mysql_fetch_array($result))
{
if (($numOfRows % 5) === 0)
{
if ($numOfRows != 0)
{
echo '</tr>';
}
echo '<tr>';
}
$numOfRows++;
if ($rows)
{
echo "<td><img src='user_images/".$rows['img_name'] . "' width='100' height='100'></td>";
}
else
{
echo "<img src='user_images/".$rows['img_name'] . "' width='100' height='100'>";
}
}
mysql_close();
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
$cols = 5;
$chunkSize = ceil(count($areaArray) / $cols);
echo $chunkSize * $cols;
foreach (array_chunk($rows, $chunkSize) as $itemsInThisTr) : ?>
<tr>
<?php foreach ($itemsInThisTr as $item) : ?>
<td><?php echo $item['img_name']; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>