PHP MySQL order table code error "cannot parse query" - php

I'm trying to get a table to sort via its header title. But I get the cannot parse query. Is it something I'm doing wrong in the MySQL?
I have to order a table of Jargon for work which contains thousands of records. So I'm just practising it at home to get it right. However at the moment I seem to be getting stuck on that MySQL bit. I followed the tips on a different website which had this code but still getting stuck a explanation of why this isn't working will help.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="../demo.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
function makeHeaderLink($value, $key, $col, $dir) {
$out = "<a href=\"" . $_SERVER['SCRIPT_NAME'] . "?c=";
//set column query string value
switch($key) {
case "Acronym":
$out .= "1";
break;
case "Full Name":
$out .= "2";
break;
case "What":
$out .= "3";
break;
default:
$out .= "0";
}
$out .= "&d=";
//reverse sort if the current column is clicked
if($key == $col) {
switch($dir) {
case "ASC":
$out .= "1";
break;
default:
$out .= "0";
}
}
else {
//pass on current sort direction
switch($dir) {
case "ASC":
$out .= "0";
break;
default:
$out .= "1";
}
}
//complete link
$out .= "\">$value</a>";
return $out;
}
switch($_GET['c']) {
case "1":
$col = "Acronym";
break;
case "2":
$col = "Full_Name";
break;
case "3":
$col = "What";
break;
}
if($_GET['d'] == "1") {
$dir = "DESC";
}
else {
$dir = "ASC";
}
if(!$link = mysql_connect("localhost", "username", "password")) {
echo "Cannot connect to db server";
}
elseif(!mysql_select_db("nazir_jargon")) {
echo "Cannot select database";
}
else {
if(!$rs = mysql_query("SELECT 'Acronym', 'Full Name', 'What' * FROM jargon1 ORDER BY $col $dir")) {
echo "Cannot parse query";
}
elseif(mysql_num_rows($rs) == 0) {
echo "No records found";
}
else {
echo "<table class=\"bordered\" cellspacing=\"0\">\n";
echo "<tr>";
echo "<th>" . makeHeaderLink("Acronym", "Acronym", $col, $dir) . "</th>";
echo "<th>" . makeHeaderLink("Full Name", "Full_Name", $col, $dir) . "</th>";
echo "<th>" . makeHeaderLink("What", "What", $col, $dir) . "</th>";
echo "</tr>\n";
while($row = mysql_fetch_array($rs)) {
echo "<tr><td>$row[person_id]</td><td>$row[Acronym]</td><td>$row[Full_Name]</td><td>$row[What]</td></tr>\n";
}
echo "</table><br />\n";
}
}
?>
</body>

Remove single quote & * from the query so that query should look like below. I hope it will work.
SELECT Acronym, Full Name, What FROM jargon1 ORDER BY $col $dir
If it won't work,
Can you print
echo "SELECT Acronym, Full Name, What FROM jargon1 ORDER BY $col $dir";
and let me know what you get?
Note: I think you wanted to use backticks(`), however mistakenly used single quote.
Edit 1
As you see
echo "SELECT Acronym, Full Name, What FROM jargon1 ORDER BY $col $dir";
prints
SELECT Acronym, Full Name, What FROM jargon1 ORDER BY ASC`
That means $col is not printing.. please check what is going wrong with $col
SELECT Acronym, Full Name, What FROM jargon1 ORDER BY columnNameMissing ASC`
^^^^^^^^^^^^^^^^^

Remove the * from your select query if you are specifying the columns returned. Otherwise get everything back with the *. One or the other.

Related

Number_format specific item in foreach php

Thanks for directing the link about the mySql API, i think there is a need to change to mySQLi or PDO. I have post the near-complete code below of same case, as my first time, could you please help what's error below, as it doesn't show the results as expected as the code using mysql_... please help. (assuming the select statement is correct please.)
<?php
$Ticker = htmlspecialchars($_GET["Ticker"]);
$StartDate = htmlspecialchars($_GET["StartDate"]);
$EndDate = htmlspecialchars($_GET["EndDate"]);
echo "<td>testing.</td>";
echo "</table>";
$pdo = new PDO('mysql:host=;dbname=, ,);
$statement = $pdo->query("Select Ticker, xxx as 'Last Update',Price, xxx as TTlUndetAmt,
FROM trade
WHERE Ticker = '$Ticker' and DATE(xxx) between '$StartDate' and '$EndDate'
GROUP BY Ticker, date
ORDER BY Ticker ASC, Date(ReleaseDT) DESC");
$row = $statement->fetch(PDO::FETCH_ASSOC);
//echo htmlentities($row['_message']);
echo "<table>";
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $value) {
if ($value === end($row)) {
echo number_format($value);
} else
{
echo $value . ",";
}
}
echo " </td></tr> " . "\n";
$i++;
}
?>
I got the results from select statement from mysql database. I use php to get the required data. I want specify the format only a specific item of each row to be numeric, i.e. (thousand separated). How could I do so? can below code do so?
Current output:
ticker1,2014-09-03 ,1.190,0,37247000
ticker2,2014-09-03 ,1.180,0,23246000
ticker3,2014-09-03 ,1.170,0,19188000
Expected Output:
ticker1,2014-09-03 ,1.190,0,37,247,000
ticker2,2014-09-03 ,1.180,0,23,246,000
ticker3,2014-09-03 ,1.170,0,19,188,000
The code I am using:
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $value) {
echo $value . ",";
if ($value === $row[5]) {
echo number_format($value);
}
}
echo " </td></tr> " . "\n";
$i++;
}
echo "</table>";
I found out that the above code will create duplicate role at the last row [5].
To my limited knowledge, I changed to
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $value) {
if ($value === end($row)) {
echo number_format($value);
} else
{
echo $value . ",";
}
}
echo " </td></tr> " . "\n";
$i++;
}
I would incorporate the key. That way, you can just check for the field name:
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $key => $value) {
echo $value . ",";
if ($key === 'YourFieldName') {
echo number_format($value);
}
}
echo " </td></tr> " . "\n";
$i++;
}
echo "</table>";
The function mysql_fetch_assoc already returns a key/value array, so you don't need anything there. Note though, that mysql_fetch_assoc is part of an old and deprecated API. If you like, have a look at: Choosing a MySQL API.
I would bring in the names, and use a $key=>$val in your foreach as such:
foreach ($row as $key=>$value)
{
echo $value . ",";
if ($key == "theRightColumn") // guessing the column name
{
echo number_format($val);
}
else
{
echo $val;
}
}
You have to change the modification in this line
foreach ($row as $value) {
to
foreach ($row AS $key => $value) {

PHP Ranking function with TIES

So I have a function that takes a number and outputs it as a placement. How do I go about making the function take in consideration ties. I have a ranking database and this php code echos out rankings on a table. right now it ranks but it doesn't consider ties. How do i go about doing this
<?php
function addOrdinalNumberSuffix($num) {
if (!in_array(($num % 100),array(11,12,13))){
switch ($num % 10) {
// Handle 1st, 2nd, 3rd
case 1: return $num.'st';
case 2: return $num.'nd';
case 3: return $num.'rd';
}
}
return $num.'th';
}
?>
<?php
$link = mysqli_connect("localhost", "citricide", "321213123Lol", "juneausmashbros");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM rankings ORDER BY points DESC";
$result = mysqli_query($link, $query);
echo '<article class="content grid_6 push_3">';
echo '<h1>';
echo 'Project M Summer Ranbat Rankings';
echo '</h1>';
echo '<section>';
echo '<center>';
echo '<table style="width:400px" class="rankslist">';
echo '<tr>';
echo '<th width="15%"><b>Rank</b></th>';
echo '<th width="45%"><b>Name</b></th>';
echo '<th width="45%"><b>Alias</b></th>';
echo '<th width="15%"><b>Points</b></th>';
echo '</tr>';
$ass = 0;
while($row = $result->fetch_array()) {
$ass++;
echo '<tr>';
if ($ass == 1) {
echo ' <center><td><B><font color=#FFD700>';
} else if ($ass == 2) {
echo ' <center><td><B><font color=#CCCCCC>';
} else if ($ass == 3) {
echo ' <center><td><B><font color=#cd7f32>';
} else {
echo '<td>';
}
echo addOrdinalNumberSuffix($ass);
echo ' </font></B</td></center>';
echo ' <td>'.$row['name'].'</td>';
echo '<td>'.$row['alias'].'</td>' ;
echo '<td>'.$row['points'].'</td>';
echo '</tr>';
}
echo '</table>';
echo '</center>';
echo '</section>';
echo '</article>';
?>
It seems like you need additional variables to track the rank and the previous value. By doing so, you can handle ties.
For example:
$ass = 0; // current record count
$rank = 0; // rank
$last_points = NULL; // variable to store last ranked value
while($row = $result->fetch_array()) {
$ass++;
// check if value changes and reset rank if it does
if ($row['points'] !== $last_points) {
$rank = $ass;
$last_points = $row['points'];
}
echo '<tr>';
if ($rank == 1) {
echo ' <center><td><B><font color=#FFD700>';
} else if ($rank == 2) {
echo ' <center><td><B><font color=#CCCCCC>';
} else if ($rank == 3) {
echo ' <center><td><B><font color=#cd7f32>';
} else {
echo '<td>';
}
echo addOrdinalNumberSuffix($rank);
echo ' </font></B</td></center>';
echo ' <td>'.$row['name'].'</td>';
echo '<td>'.$row['alias'].'</td>' ;
echo '<td>'.$row['points'].'</td>';
echo '</tr>';
}
So say your points looked like this:
100
100
90
80
The $rank value would be:
1
1
3
4

While loop within a while loop logically not working in PHP

I have this while loop within another while loop in my PHP:
$selecty = mysql_query("SELECT * FROM followers WHERE userid='".$_SESSION['id']."'");
$rowsy = mysql_num_rows($selecty);
echo '<td>'. $table["username"]. '</td>';
echo '<td>';
while ($tables = mysql_fetch_assoc($selecty)) {
if($tables['followerid']!=$table['id']) {
echo ''.'';
} else {
echo ''.'';
}
}
echo '</td>';
echo "<tr>";
This is more of a logic question and whether or not a nested while loop is the right way to do it. What I'm trying to say is if the 'followerid' from 'user followers table' is not the same as the 'id' from users table (which is from the previous loop) - echo the follow button, else echo the following button.
This is working file while I have data in the followers table but If I don't nothing shows (as there are no rows) - How could I implement this in my PHP? So also if there are no rows in 'followers table' echo follow button?
you can try do it like that
$selecty = mysql_query("SELECT * FROM followers WHERE userid='".$_SESSION['id']."'");
$rowsy = mysql_num_rows($selecty);
echo '<td>'. $table["username"]. '</td>';
echo '<td>';
while ($tables = mysql_fetch_assoc($selecty)) {
if($tables['followerid']!=$table['id'] and $tables['followerid'] != '') {
echo '';
} else if($tables['followerid'] =$table['id'] and $tables['followerid'] !='') {
echo '';
} else {
echo what you like here when $tables['followerid'] = ''
}
}
echo '</td>';
echo "<tr>";
edit
class="follow">'.'</a>'
^------------you dont have to make point and single quotes here
$selecty = mysql_query("SELECT * FROM followers WHERE userid='".$_SESSION['id']."'");
$rowsy = mysql_num_rows($selecty);
echo '<table><tr>';
echo '<td>'. $table["username"]. '</td></tr>';
if ($tables['followerid'] !== ''){
while ($tables = mysql_fetch_assoc($selecty)) {
echo '<tr><td>';
if($tables['followerid']!=$table['id'] and $tables['followerid'] != '') {
echo '</td></tr>';
} else if($tables['followerid'] =$table['id'] and $tables['followerid'] !='') {
echo '</td></tr>';
} else {
echo "what you like here </td></tr>";
}
}
}
else {
echo "do your code here " ;
}
echo "</table>";
Put a boolean (FALSE) at the start of the 'followers' loop such that if it gets crossed make it TRUE. If you get outside the loop and it's still FALSE then add the button anyway.
$trip = FALSE;
while ($tables = mysql_fetch_assoc($selecty)) {
if($tables['followerid']!=$table['id']) {
echo ''.'';
} else {
$trip = TRUE;
echo ''.'';
}
}
if( !$trip ) echo '<a href="#" data-userid="'.$_SESSION['id'].'" class="follow">'.'</a

How I can simplify this PHP code? too many switch() function

I made listview in jQuery Mobile and I used PHP to feed its contents. It works properly, but the code is too long and most part of it are very similar to each other. Is there any way to simplify the code? Please have a look at the code, then I'll explain what I really need to do:
<ol data-role="listview">
<?php
while ($row = mysql_fetch_array($result)){
echo "<li><a href=\"#\">";
// first column check
switch ($row[1]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
}
// second column check
switch ($row[2]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
echo " N . ";
}
// third column check
switch ($row[3]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
echo " N . ";
}
// fourth column check
switch ($row[4]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
echo " N . ";
}
// fifth column check
switch ($row[5]) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
echo " N . ";
}
// sixth column check
switch ($row[6]) {
case "Behnam":
echo " B ";
break;
case "Tarin":
echo " T ";
break;
default:
echo " N ";
}
echo "</li></a>";
}
?>
</a></li>
</ol>
and the result is:
By using while ($row = mysql_fetch_array($result)){ I can fetch each row of the sql table one by one. But I also need to check the value of each cell(column) as well.
Group the code in a 2 parameter function:
function checkRowValue($row, $checkDefault) {
switch ($row) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
default:
if ($checkDefault)
echo " N . ";
}
}
Invoke as:
<ol data-role="listview">
<?php
while ($row = mysql_fetch_array($result)){
echo "<li><a href=\"#\">";
// first column check
for ($i = 0; $i < 7; $i++)
checkRowValue($row[i], $i > 0);
}
This generalizes it by applying a function over all the columns in your row (skipping first) and then string them together with " . ".
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "<li><a href=\"#\">";
echo join(' . ', array_map(function($v) {
if ($v == 'Behnam') {
return 'B';
elseif ($v == 'Tarin') {
return 'T';
else {
return 'N';
}
}, array_slice($row, 1));
echo "</li></a>";
}
Try This
if(in_array("Behnam",$row) {
echo " B . ";
}
else if(in_array("Train",$row) {
echo " T . ";
}
else {
echo " N . ";
}
This is the final result:
<ul id="competition_list" data-role="listview" data-inset="true" data-theme="a">
<?php
// using the returned value from database to feed the list.
// showing the competiton rounds' outcome.
while ($row = mysql_fetch_array($result)){
echo "<li><a href=\"#\">";
echo $row[0] . "."; //this is the id column in the table and will give me the number of the row
for($i = 1; $i <= 5; $i++){
switch ($row[$i]) {
case "Behnam":
echo " B ";
break;
case "Tarin":
echo " T ";
break;
}
} // end for()
echo "</a></li>";
} // end while()
?>
</ul>
<?php
while ($row = mysql_fetch_array($result)){
echo "<li><a href=\"#\">";
// first column check
foreach($row as r)
{
switch (r) {
case "Behnam":
echo " B . ";
break;
case "Tarin":
echo " T . ";
break;
}
}
?>

PHP search page problems

I have written this code for a search page in PHP and I would like to know a way to make the search results more accurate. Some search strings will pull up everything in the database because it contains that word. Here is my code
<?php include("header.php");?>
<h3>Rental Search Results</h3>
<div class="searchbox">
<form method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="usersearch">Search Rentals Now:</label>
<input type="text" name="usersearch" value="<?php echo $_GET['usersearch']; ?>" />
<input type="submit" name="submit" value="Search" />
</form>
</div>
<br />
<br />
<?php
// This function builds a search query from the search keywords and sort setting
function build_query($user_search, $sort) {
$search_query = "SELECT * FROM online_rental_db";
// Extract the search keywords into an array
$clean_search = str_replace(',', ' ', $user_search);
$search_words = explode(' ', $clean_search);
$final_search_words = array();
if (count($search_words) > 0) {
foreach ($search_words as $word) {
if (!empty($word)) {
$final_search_words[] = $word;
}
}
}
// Generate a WHERE clause using all of the search keywords
$where_list = array();
if (count($final_search_words) > 0) {
foreach($final_search_words as $word) {
$where_list[] = "Description LIKE '%$word%' OR Manufacturer LIKE '%$word%' OR Model LIKE '%$word%' OR Category LIKE '%$word%'";
}
}
$where_clause = implode(' OR ', $where_list);
// Add the keyword WHERE clause to the search query
if (!empty($where_clause)) {
$search_query .= " WHERE $where_clause";
}
// Sort the search query using the sort setting
switch ($sort) {
// Ascending by job title
case 1:
$search_query .= " ORDER BY Description";
break;
// Descending by job title
case 2:
$search_query .= " ORDER BY Description DESC";
break;
// Ascending by state
case 3:
$search_query .= " ORDER BY Manufacturer";
break;
// Descending by state
case 4:
$search_query .= " ORDER BY Manufacturer DESC";
break;
// Ascending by date posted (oldest first)
case 5:
$search_query .= " ORDER BY Model";
break;
// Descending by date posted (newest first)
case 6:
$search_query .= " ORDER BY Model DESC";
break;
default:
// No sort setting provided, so don't sort the query
}
return $search_query;
}
// This function builds navigational page links based on the current page and the number of pages
function generate_page_links($user_search, $sort, $cur_page, $num_pages) {
$page_links = '';
// If this page is not the first page, generate the "previous" link
if ($cur_page > 1) {
$page_links .= '<- ';
}
else {
$page_links .= '<- ';
}
// Loop through the pages generating the page number links
for ($i = 1; $i <= $num_pages; $i++) {
if ($cur_page == $i) {
$page_links .= ' ' . $i;
}
else {
$page_links .= ' ' . $i . '';
}
}
// If this page is not the last page, generate the "next" link
if ($cur_page < $num_pages) {
$page_links .= ' ->';
}
else {
$page_links .= ' ->';
}
return $page_links;
}
// Grab the sort setting and search keywords from the URL using GET
$user_search = $_GET['usersearch'];
// Calculate pagination information
$cur_page = isset($_GET['page']) ? $_GET['page'] : 1;
$results_per_page = 5; // number of results per page
$skip = (($cur_page - 1) * $results_per_page);
// Start generating the table of results
echo '<table class="results">';
echo '<td align="center">Description</td><td align="center">Manufacturer</td><td align="center">Model #</td><td align="center">Image</td>';
// Generate the search result headings
echo '<tr class="bottomborder">';
echo '</tr>';
// Connect to the database
require_once('connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Query to get the total results
$query = build_query($user_search,'');
$result = mysqli_query($dbc, $query);
$total = mysqli_num_rows($result);
$num_pages = ceil($total / $results_per_page);
// Query again to get just the subset of results
$query = $query . " LIMIT $skip, $results_per_page";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
$description = $row['Description'];
$model = $row['Model'];
$manufacturer = $row['Manufacturer'];
$image = $row['Image'];
$hour = $row['Hour'];
$day = $row['Day'];
$week = $row['Week'];
$month = $row['Month'];
$file = $row['PDF'];
$ID = $row['ID'];
$Category = $row['Category'];
$CTGID = $row['CTGID'];
if ($image == "") {
$image = "No Image";
}else {
$image = "<a class=\"thumbnail\" href=\"pp.php?ID=$ID\"><img class=\"rental_image\" src=\"$image\"><span><img src=\"$image\" ><br> $description</span></a>";
}
echo '<tr>';
echo "<td align=\"center\" valign=\"middle\" width=\"25%\">$description</td>";
echo "<td align=\"center\" valign=\"middle\" width=\"25%\">$manufacturer</td>";
echo "<td align=\"center\" valign=\"middle\" width=\"25%\">$model</td>";
echo "<td align=\"center\" valign=\"middle\" width=\"25%\">$image</td>";
echo '</tr>';
}
echo '</table>';
// Generate navigational page links if we have more than one page
if ($num_pages > 1) {
echo generate_page_links($user_search, '', $cur_page, $num_pages);
}
mysqli_close($dbc);
?>
<?php include("footer.php");?>
</div>
</body>
</html>
I would use a fulltext index with match against.
Kindly use the AND not OR. Example
Searching 4 word:
Hello, How, are, you
With OR it looks like:
like '%Hello%' or .. like '%How%' or .. like '%are%' or ... '%you%'
Now want would happen in a row any of the four words found it is selected and displayed.
With AND it looks like:
like '%Hello%' and .. like '%How%' and .. like '%are%' and ... '%you%'
Now only the row which has the four words would be only selected.
Your can also say that in any row as Apples or Oranges would be selected,
In AND Apples and Oranges means only having both things is required.

Categories