How do I properly convert a mySQL query to PDO - php

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){

Related

PHP pagination isn't working and I'm not sure why

I feel like I ask a lot of questions.
Anyways, I'm writing pagination for some database entries, and it looks sound to me but it's only displaying the first 10 posts and nothing else when I click the links.
The whole shebang is right here:
<?php
$post_limit = 10;
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("failed to connect: " . $conn->connect_error);
}
$sql = "SELECT count(id) FROM $tablename";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo "you fucked up";
} else {
echo $row["id"];
}
$row = mysqli_fetch_array($result, MYSQL_NUM);
$post_count = $row[0];
if(isset($_GET['page'])) {
$page = $_GET['page'] + 1;
$offset = $post_limit * $page;
} else {
$page = 0;
$offset = 0;
}
$post_left = $post_count - ($page * $post_limit);
$sql = "SELECT id, upvotes, downvotes, name, title, message, date, time FROM posts ORDER BY date DESC, time DESC LIMIT $offset, $post_limit";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<br><div id='messageBar'>";
echo " ❖ </b>";
echo "Posted by <b>";
echo htmlspecialchars($row["name"]);
echo "</b> on ";
echo $row["date"];
echo " at ";
echo $row["time"];
if (!empty($row['title'])) {
echo " - <b>";
echo htmlspecialchars($row["title"]);
echo "</b>";
}
echo "<span style='float: right'>#";
echo $row["id"];
echo "</span>";
echo "</div><div id='messageContent'>";
echo htmlspecialchars($row["message"]);
echo "<br><br><span id='commentLink'><a class='commentLink' href='thread.php?id=$row[id]'>view thread </a></span>";
echo "<br></div><br><hr>";
}
} else {
echo "<br>";
echo "<center><i>it's dusty in here</i></center>";
echo "<br>";
}
if ($page > 0) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a> | ";
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($page == 0) {
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($post_left < $post_limit) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a>";
}
$conn->close();
?>
The link for the next page appears at the bottom, but clicking it takes you to the page you're already on with the same 10 most recent posts.
I am trying to learn PHP as I go, so I appreciate any help. Thank you!
Instead of using $_GET please use $_SESSION to manage a counter.
Every time you go in this page you increment the counter.
So, you have to do this on the top of the page:
if(isset($_SESSION['counter'])) {
$page = $_SESSION['counter'] + 1;
$offset = $post_limit * $page;
} else {
$page = 0;
$offset = 0;
$_SESSION['counter']=0;
}
Try this.
By the way there is Datatables which do what you're looking for.
P.S. If you don't start sessions in some other points in your code, please put session_start(); in the first page (e.g., login.php) otherwise put on this page.
Fixed. Problem was here:
if ($page > 0) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a> | ";
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($page == 0) {
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($post_left < $post_limit) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a>";
}
The URL I was linking to wasn't supposed to have spaces around the = sign. It's still buggy, but it works.

Search/Query in a large table with many records

I've created a html+php page wherein it searches in a mysql database. I am able to get output when my table contains a few records but when my table has over 100+ records it would no longer show records when i search and shows my else statement which is "0 records".
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(!empty($sfname) || !empty($sgen) || !empty($sdoc) || !empty($smisc) || !empty($ssick) || !empty($sothers) ){
$genQueryPart = !empty($sgen) ? "Gender LIKE '%$sgen%'" : "";
$fnameQueryPart = !empty($sfname) ? "FullName LIKE '%$sfname%'" : "";
$docQueryPart = !empty($sdoc) ? "Doctor LIKE '%$sdoc%'" : "";
$miscQueryPart = !empty($smisc) ? "Misc LIKE '%$smisc%'" : "";
$sickQueryPart = !empty($ssick) ? "Sickness LIKE '%$ssick%'" : "";
$othersQueryPart = !empty($sothers) ? "Others LIKE '%$sothers%'" : "";
$arr = array($genQueryPart, $fnameQueryPart,$docQueryPart,$miscQueryPart,$sickQueryPart,$othersQueryPart);
$sql = "select * from index where ";
$needsAnd = false;
for ($i = 0; $i < count($arr); $i++) {
if ($arr[$i] != "") {
if ($needsAnd) {
$sql .= " AND ";
}
$needsAnd = true;
$sql .= " " . $arr[$i];
}
}
//Get query on the database
$result = mysqli_query($conn, $sql);
mysqli_store_result();
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>File ID</th>";
echo "<th>Full Name</th>";
echo "<th>Gender</th>";
echo "<th>Doctor</th>";
echo "<th>Misc</th>";
echo "<th>Sickness</th>";
echo "<th>Others</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['FileID']."</td>";
echo "<td>".$row['FullName']."</td>";
echo "<td>".$row['Gender']."</td>";
echo "<td>".$row['Doctor']."</td>";
echo "<td>".$row['Misc']."</td>";
echo "<td>".$row['Sickness']."</td>";
echo "<td>".$row['Others']."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
echo "0 results";
}
} else {
echo "You must enter at least one value";
}
mysqli_close($conn);
?>
Use if condition and paging to show more than 100 records after search. count the number of results after that use paging query to show records per page .This will be good idea for displaying large number of records.
Don't Merge Php and Html together . fetch the record in a function and use is to integrate in HTML

Links does not show correct data

I am facing a problem, and i don't know how to fix it.
If i click a link generated from this php, the results are same as displayed on 1st page. For example view.php?page=2 displays same data as view.php?page=1 or 3, etc.
That happens for 'view.php?ID=' aswell.
<?php
require_once('connection.php');
require_once('auth.php');
echo "<br /><br /><font color=red size='6'><center>Facturi emise</center></font><br /><br />";
$query = "SELECT * FROM out_fact ORDER BY ID DESC LIMIT 0, 20";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
if (mysql_num_rows($result) > 0) {
echo "<table cellpadding=10 border=1 align=center>";
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>"."<a href=javascript:window.open('view.php?ID=".$row[0]."','NAME','location=false')><font color=blue size='4'><center>".$row[1]." din data de ".$row[2]."</a></center>"."</font></td>";
echo "<td>"."<font color=red size='4'><center>".$row[3]." ".$row[12]."</center></font></td>";
echo "</tr>";
};
echo "</table>";
}
else {
echo "No rows found!";
}
echo "<tr><td> <a href='view.php?ID=".$row[0]."'>".$row[1]."</a></td></tr>";
mysql_free_result($result);
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 20;
$sql = "SELECT COUNT(ID) FROM out_fact";
$query = mysql_query($sql);
$result = mysql_fetch_row($query);
$total_records = $result[0];
$total_pages = ceil($total_records / 20);
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='view.php?page=".$i."'>".$i."</a> ";
};
?>
How to post correct data, or what's missing. I'm new in php coding...
Thanks in advance.
Try at least using MySQLi instead of deprecated MySQL. And what you are trying to do is called Pagination.
connection.php:
<?php
$con=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase"); /* REPLACE THE NECESSARY HOST, USERNAME, PASSWORD, AND DATABASE */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
Your main file:
<?php
include('connection.php');
require_once('auth.php');
echo "<br><br><font color=red size='6'><center>Facturi emise</center></font><br><br>";
$query = "SELECT * FROM out_fact ORDER BY ID DESC";
$result = mysqli_query($con,$query);
$count=mysqli_num_rows($result);
$r = mysqli_fetch_row($result);
$numrows = $r[0];
$rowsperpage = 10; /* NUMBER OF ROWS TO SHOW PER PAGE */
$totalpages = ceil($count / $rowsperpage);
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
} else {
$currentpage = 1;
}
if ($currentpage > $totalpages) {
$currentpage = $totalpages;
}
if ($currentpage < 1) {
$currentpage = 1;
}
$offset = ($currentpage - 1) * $rowsperpage;
$result=mysqli_query($con,"SELECT * FROM out_fact ORDER BY ID DESC LIMIT $offset,$rowsperpage");
echo "<table cellpadding=10 border=1 align=center>";
while($row = mysqli_fetch_array($result)){
/* JUST REPLACE THE NECESSARY DATA YOU WANT TO INPUT INSIDE THIS WHILE LOOP */
$rowdata=mysqli_real_escape_string($con,$row[0]);
echo "<tr>";
echo "<td><a href='view.php?ID=$rowdata&location=false' target='_blank'><font color=blue size='4'><center>".$row[1]." din data de ".$row[2]."</a></center>"."</font></td>"; /* JUST REPLACE THE NECESSARY DATA IN THE LINK IF YOU MUST */
echo "<td>"."<font color=red size='4'><center>".$row[3]." ".$row[12]."</center></font></td>";
echo "</tr>";
} /* END OF WHILE LOOP */
if($count==0){
echo "<tr><td></td><td>No results found.</td><td></td></tr>";
}
else { /* START OF PAGINATION LINK */
echo '<tr height="30px;" valign="bottom"><td></td><td>';
echo "<table style='border-collapse:separate; border-spacing:3px;'><tr>";
/****** build the pagination links ******/
$range = 2;
if ($currentpage > 1) {
$prevpage = $currentpage - 1;
echo "<td style='width:70px; background-color:fff; border:solid #08c 1px; font-size:14px;' align='center'> <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage' style='background-color:fff;'>Previous</a> </td>";
}
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
if (($x > 0) && ($x <= $totalpages)) {
if ($x == $currentpage) {
echo "<td style='width:20px; background-color:fff; font-size:14px; border:solid #ccc 2px;' align='center'> <font color='#ccc'><b>$x</b></font> </td>";
} else {
echo "<td style='width:20px; background-color:fff; font-size:14px; border:solid #08c 1px;' align='center'> <a href='{$_SERVER['PHP_SELF']}?currentpage=$x' style='background-color:fff;'>$x</a> </td>";
}
}
}
if ($currentpage != $totalpages) {
$nextpage = $currentpage + 1;
echo "<td style='width:70px; background-color:fff; font-size:14px; border:solid #08c 1px;' align='center'> <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage' style='background-color:fff;'>Next</a> </td>";
} // end if
/****** end build pagination links ******/
echo "</tr></table></td></tr>";
} /* END OF ELSE IF COUNT 0 */
echo '</table>';
?>

mysql_fetch_array() expect parameter 1

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."'";

PHP Insert Multidimensional Array into mysql

i try to store the booking booths into database based on user selection, there are 10 check boxes for each booths and user can choose which day they want to reserve booths. For each check box has it own field in database, if user choose booth A01, D1 and D2, when he press reserve button, it will insert value into D1 and D2. But I dont know how to get the checked checkbox value to store in database
my booth interface
http://i.imgur.com/umYcI.gif
my table structure
http://i.imgur.com/vKh6R.gif
My coding
<?php
session_start();
if ( !isset($_SESSION['AUTHORIZED_USERNAME']) || empty($_SESSION['AUTHORIZED_USERNAME']) ) {
header("location:index.php");
}else{
$user=$_SESSION['AUTHORIZED_USERNAME'];
}
include('db.php');
if($_REQUEST){
$id = $_REQUEST['search_category_id'];
$query2 = mysql_query("SELECT filenameBig, filename, url FROM eventinfo where eventID ='$id'");
$row = mysql_fetch_array($query2, MYSQL_ASSOC);
if($id == -1)
{
echo "<style type='text/css'>#btn_submit{visibility:hidden}</style>";
}
else{
/*echo "<a href='{$row['url']}'>Click me!</a>";*/
echo "<p><br><img src='{$row['filename']}' alt='' /></p>";
echo "<p></p>";
echo "<p align='right'><a href='$row[filenameBig]' target='_blank'>Click to view large image</a></p>";
echo "<hr size='1'>";
echo "<div style='padding-left:4px;' align='left'><strong>Booths Listing</strong>";
echo "<p></p>";
$query = "select boothAlias, totalDay from booths, eventinfo where booths.eventID=eventinfo.eventID && booths.eventID = ".$id."";
$_SESSION['EVENT_ID']=$id;
$result = mysql_query($query);
$result2= mysql_query($query);
echo "<table border='0' style='width:400px;table-layout:fixed' >";
$rows2 = mysql_fetch_array($result);
$Day=$rows2['totalDay'];
echo "<table>";
for ($day = 0; $day <= $Day; ++$day) {
if($day==0){
echo "<th>Booth</th>";
}else{
echo "<th>D".$day."</th>";
}
}
while($rows = mysql_fetch_array($result2)){
$boothAlias=$rows['boothAlias'];
$totalDay=$rows['totalDay'];
echo "<tr><td>$boothAlias</td>";
for ($day2 = 1; $day2 <= $totalDay; ++$day2) {
echo "<td><input name='day2[]' type='checkbox' value='$day2' /></td>";
}
echo "</tr>";
}
echo "</table>";
}
}
?>
I think that SET type would be good solution for this.
http://dev.mysql.com/doc/refman/5.0/en/set.html

Categories