PHP - $query Returning No Database Results
Hello all,
Trying to figure out how to display database results so that they are numbered (for editing and deletion purposes). I want to be able to edit the message text and update the database information with the UPDATE command, but have not gotten that far yet. Current problem is that I am returning no results. Here is my script: Code: [Select] <!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=iso-8859-1" /> <title>My Profile</title> <link href="loginmodule.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>My Profile </h1> <a href="member-index.php">Home</a> | <a href="member-profile.php">My Profile</a> | Update Posts | <a href="logout.php">Logout</a> <br /><br /> <?php $subject = $_POST['subject']; $message_text = $_POST['message_text']; //Connect to mysql server $link = mysql_connect('XXXXXX', 'XXXXXX', 'XXXXXX'); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } //Select database $db = mysql_select_db('ryan_iframe'); if(!$db) { die("Unable to select database"); } // validate incoming values $subject = (isset($_GET['subject'])) ? (int)$_GET['subject'] : 0; $message_text = (isset($_GET['message_text'])) ? (int)$_GET['message_text'] : 0; ob_start(); $id = $_GET['SUBJECT']; $query = sprintf( " SELECT SUBJECT, MSG_TEXT, UNIX_TIMESTAMP(MSG_DATE) AS MSG_DATE FROM FORUM_MESSAGE WHERE SUBJECT = '$id' ORDER BY MSG_DATE DESC", DB_DATABASE, DB_DATABASE, $subject, $subject); $result = mysql_query($query) or die(mysql_error()); $num = mysql_numrows($result); mysql_close(); $i = 0; while ($i < $num) { $subject = mysql_result($result, $i, "SUBJECT"); $message_text = mysql_result($result, $i, "MSG_TEXT"); echo '<div style="width: 400px;padding:20px;">'; echo '<table border=0 width="400px">'; echo '<tr>'; echo '<td style="vertical-align:top;width:auto;">'; echo 'Date: '; echo '</td>'; echo '<td style="vertical-align:top;width:320px;">'; echo date('F d, Y', $row['MSG_DATE']) . '</td>'; echo '</tr>'; echo '<tr>'; echo '<td style="vertical-align:top;width:auto;">'; echo 'Subject: '; echo '</td>'; echo '<td style="vertical-align:top;width:320px;">'; echo '<div>' . htmlspecialchars($row['SUBJECT']) . '</div>'; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td style="vertical-align:top;width:auto;">'; echo 'Message: '; echo '</td>'; echo '<td style="vertical-align:top;width:320px;">'; echo '<div>' . htmlspecialchars($row['MSG_TEXT']) . '</div>'; echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td style="vertical-align:top;width:auto;">'; echo '</td>'; echo '<td style="vertical-align:top;width:320px;text-align:center;">'; echo '<form method="post">'; echo '<input type="hidden" name="update" value="true" />'; echo '<input type="submit" value="Update" />'; echo ' '; echo '<input type="hidden" name="delete" value="true" />'; echo '<input type="submit" value="Delete" />'; echo '</form>'; echo '</td>'; echo '</tr>'; echo '</table>'; echo '<br />'; echo '<hr />'; echo '</div>'; ++$i; } ?> </body> </html> Thanks in advance. Ryan Similar TutorialsGreetings all! I've been working on a project for about a week now and everything had been going fine until this evening. I'm querying a single row from a user information table based on the userID and doing various things based off of the information that is returned. For whatever reason, the query is not returning all of the information anymore. Code follows: Code: [Select] $userToEdit = mysqli_real_escape_string($GLOBALS['link'], $_POST['userToEdit']); $userSQL = "SELECT fName, lName, email, volunteer, staff, admin, active, volunteerID FROM userinfo WHERE userID=" . $userToEdit; $result = mysqli_query($GLOBALS['link'], $userSQL); if (!$result) { $message = 'There was an error retrieving the user information from the database.'; include '../html/error.html.php'; exit(); } $editInfo = mysqli_fetch_assoc($result); The strange part is that the database i'm querying is located on my remote host(GoDaddy). When I run the app from my local Apache server and query the remote DB, everything works fine, however, when I upload the files to my host, not all of the information is being returned. For example, using the print_r() function while on my local host, i get: Code: [Select] Array ( [fName] => Taylor [lName] => Hughes [email] => taylor@gmail.com [volunteer] => 1 [staff] => 0 [admin] => 0 [active] => 1 [volunteerID] => 13 ) But when I execute the app on my remote host, the print_r() function outputs: Code: [Select] Array ( [fName] => Taylor [lName] => Hughes [email] => taylor@gmail.com [volunteer] => [staff] => [admin] => [active] => [volunteerID] => 13 ) I'm not sure why this is happening but it is affecting multiple queries and subsequently multiple forms and functionality in different parts of the application. Any thoughts or suggestions would be greatly appreciated. I've browsed around for about an hour with no luck. I'm writing in PHP 5.3 and the remote MySQL DB is version 5.0 Oh! And if it helps, I just came to the realization that all the items not being returned are of the BIT data type in the tables. What would be the correct way to close a mysql query? At current the second query below returns results from the 1st query AND the 2nd query The 3rd query returns results from the 1st, 2nd and 3rd query. etc etc. At the moment I get somthing returned along the lines of... QUERY 1 RESULTS Accommodation 1 Accommodation 2 Accommodation 3 QUERY 2 RESULTS Restaurant 1 Restaurant 2 Restaurant 3 Accommodation 1 Accommodation 2 Accommodation 3 QUERY 3 RESULTS Takeaways 1 Takeaways 2 Takeaways 3 Restaurant 1 Restaurant 2 Restaurant 3 Accommodation 1 Accommodation 2 Accommodation 3 Code: [Select] <!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" /> <?php include($_SERVER['DOCUMENT_ROOT'].'/include/db.php'); ?> <title>Untitled Document</title> <style type="text/css"> <!-- --> </style> <link href="a.css" rel="stylesheet" type="text/css" /> </head><body> <div id="listhold"> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Placestostay.html">Places To Stay</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Accommodation' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Eatingout.html">Eating Out</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Restaurant' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------------------------------------------------------------------------------> <div class="list"><a href="Eatingin.html">Eating In</a><br /> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Takeaways' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> <!------------------------------------------------------------------------------SKILLED TRADES BELOW---------------------------------------------------> <div class="list"><a href="Skilledtrades.html">Skilled Trades</a><br/> <?php $title ="TITLE GOES HERE"; $query = mysql_query("SELECT DISTINCT subtype FROM business WHERE type ='Skilled Trades' AND confirmed ='Yes' ORDER BY name"); echo mysql_error(); while($ntx=mysql_fetch_row($query)) $nt[] = $ntx[0]; $i = -1; foreach($nt as $value) {$i++; $FileName = str_replace(' ','_',$nt[$i]) . ".php"; $FileUsed = str_replace('_',' ',$nt[$i]); echo "<a href='" . str_replace(' ','_',$nt[$i]) . ".php?title=$title&subtype=$FileUsed'>" . $nt[$i] . "</a>" . "<br/>"; $FileHandle = fopen($FileName, 'w') or die("cant open file"); $pageContents = file_get_contents("header.php"); fwrite($FileHandle,"$pageContents");} fclose($FileHandle); ?> </div> Hi All, Its been a while since i've posted, its good to be back. I am currently trying to pull two exchange rates against the $ using YQL's restful url. Unfortunately I am having a huge problem returning the results correct.... currently my array will only output a single rate (instead of two) and the hash array returns with the base rate name rather than the expected currency code. I hope someone can help me sort this as it's given me quite a headache! Please see the code below: Code: [Select] <?php require_once('uwe_proxy.php'); /* * To change this template, choose Tools | Templates * and open the template in the editor. */ # use the yahoo YQL rest service to return any number of rates in a hash function get_yahoo_rest_rate ($base, $curr_arr) { $params = ''; $rates = array(); # define the YQL rest url head & tail $yql_base_uri = "http://query.yahooapis.com/v1/public/yql"; $yql_tail_uri = '&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys'; # build up the $params value foreach($curr_arr as $curr) { $params .= $curr.$base.','; } #strip last comma $params = substr($params, 0, -1); # build the query with the params as comma sep. string eg. USDGBP,USDBOB,.. $yql_query = "select * from yahoo.finance.xchange where pair IN ('{$params}')"; # build the the complete YQL query $yql_query_url = $yql_base_uri . "?q=" . urlencode($yql_query) . $yql_tail_uri; # send the query via proxy and get as string and load as simplexml object $yql_response = @simplexml_load_string(file_get_contents_proxy($yql_query_url)); Print_r($yql_query_url); //- debugging only # process simplexml object and return a sorted hash of rates or FALSE on error if ($yql_response) { foreach($yql_response->results->rate as $rate) { if ((float)$rate->Rate>0) { $rates[substr((string)$rate->attributes()->id, -3)] = (float)$rate->Rate; } } ksort($rates); return $rates; } else { return FALSE; }// print_r($yql_response); - debugging only } /////// - debugging only $curr_arr = array('GBP','GBP'); $rates = get_yahoo_rest_rate ('USD', $curr_arr); //PRINT_R($yql_response); print_r($rates); ?> Sorry about dumping the whole lot - but I really don't know where this is going wrong! Thanks in Advance for any help or pointers in the right direction! Well, the title says it all, I do have a class named Database and one Users with multiple methods (code below). When i do try to use one user method (find_all) it returns 2 identical results from the database (and there is only one record in the DB). I tried to spot some mistake in the code but i couldn't find it, if you find something please tell... Database Class: Code: [Select] <?php /** * Class Name: MySQLDatabase * * Most of the methods in this class are * database-neutral methods for code reusability. * * Author: hisk */ require_once("config.php"); class MySQLDatabase { private $connection; private $last_query; private $magic_quotes_active; private $real_escape_string; function __construct() { $this->open_connection(); $this->magic_quotes_active = get_magic_quotes_gpc(); $this->real_escape_string = function_exists("mysql_real_escape_string"); } public function open_connection() { $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS); if(!$this->connection) { die("Database connection failed: " . mysql_error()); } else { $db_select = mysql_select_db(DB_NAME, $this->connection); if (!$db_select) { die("Database selection failed: " . mysql_error()); } } } public function close_connection() { if(isset($this->connection)) { mysql_close($this->connection); unset($this->connection); } } public function query($sql) { $this->last_query = $sql; $result = mysql_query($sql, $this->connection); $this->confirm_query($result); return $result; } private function confirm_query($result) { // usable only in query() function (private) if(!$result) { echo "DB Query Failed: " . mysql_error(); // The last query that might got us the problem echo "Last Query Was: " . $this->last_query; } } // agnostic public function num_rows($result) { return mysql_num_rows($result); } public function affected_rows($result) { return mysql_affected_rows($result); } public function insert_id($result) { return mysql_insert_id($result); } public function fetch_array($result) { return mysql_fetch_array($result); } public function escape_value($value) { if($this->real_escape_string) { // undo any magic quote effect so mysql_real_esc_str can work if($this->magic_quotes_active) { $value = stripslashes($value);} $value = mysql_real_escape_string($value); } else { if (!$this->magic_quotes_active) { $value = addslashes($value); } } return $value; } } $database = new MySQLDatabase(); ?> User Class: Code: [Select] <?php // smart to include the database class require_once("database.php"); class User { public static function find_by_id($id=0) { global $database; $result_set = self::find_by_sql("SELECT * FROM users WHERE id = {$id}"); $result = $database->fetch_array($result_set); return $result; } public static function find_all() { global $database; $result_set = self::find_by_sql("SELECT * FROM users"); return $result_set; } public static function find_by_sql($sql="") { global $database; $result_set = $database->query($sql); return $result_set; } } ?> TEST FILE: Code: [Select] <?php require_once("../includes/database.php"); require_once("../includes/user.php"); $users = User::find_all(); $result = $database->fetch_array($users); foreach($result as $user) { echo "<pre>" . $user . "</pre>"; } ?> I'm having trouble with a simple SELECT query. I just cannot figure out what the problem is... <?php //Include database connection details include 'login/config.php'; //Connect to mysql server $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } //Select database $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } $qry="SELECT * FROM members"; $result = mysqli_query($link, $qry); echo "<table>"; while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) { $getid = ($row['member_ID']); $firstname = ($row['firstname']); $lastname = ($row['lastname']); $email = ($row['email']); echo "<tr><td>$firstname</td><td>$email</td></tr>"; } echo "</table>"; ?> I know I have a connection to the DB, and I know that the query will return values as I have tested in in phpmyadmin. Can anyone see anything obvious I am missing? Thanks Hey all, First off, if this is in the wrong section I apologize. I wasn't sure if it should be here or the mySQL section. What's going on is, I'm in the process of learning the Prepared Statement way of doing things and am changing / updating my code to reflect the changes. Everything was going fine until I attempted to do what I could do using old MySQL methods and that is display the queried results on the same page. I can place a query and display the results as they should be displayed if I only use one block of code. However, if I try to do any additional queries on the same page, they get killed and do not display anything even though I know the query is fine because I can test the exact same syntax below one a different page and it works. Here's a code snippet for an example: Code: [Select] Code: <table> <tr> <td> // The below code will display a selection box containing various strings such as "hello world", "great to be here", "Wowserz", "this is mind blowing" etc. that are stored in the database. <?php echo "<select = \"SpecialConditions\">"; if($stmt->num_rows == NULL){ echo "No results found."; }else{ while($stmt->fetch()){ echo "<option value=\"$specialId\">$specialcondition</option>"; } } echo "</select>"; ?> </td> <td> // If I place another fetch query below the above fetch() query, this one will not show up. This one is supposed to display values 1 - 20 that have been stored in the DB. <?php echo "<select = \"NumberSets\">"; if($stmt->num_rows == NULL){ echo "No results found."; }else{ while($stmt->fetch()){ echo "<option value=\"".$numbers."\">".$numbers."</option>"; } } echo "</select>"; ?> </td> </tr> </table> What am I doing wrong with this? When I use regular SQL queries I can display multiple results on the same page. The results are being pulled from two separate joined tables but I don't think that's the issue. Say a user puts in a support request, and for every request it generates a unqiue string, and enters it into the database. Ok, now say there is a text field, when the user enters their unique string and it finds a match, it displays the data along with it. How can I accomplish this? Im kind of new to mysql, but I know basic SQL. Would be great if somebody could point me in the right direction! Thanks My aim is for this what if the table is empty which means no results will be retrieved in the first query then I want it to repeat the $testArray as "TBD" as well. Code: [Select] function getTop5() { $this->db->select('character1_id, character2_id, character3_id, character4_id, character5_id'); $this->db->from('site_top5'); $this->db->where('status_id', '1'); $this->db->order_by('id', 'desc'); $query = $this->db->get(); $row = $query->row(); $ids = array( $row->character1_id, $row->character2_id, $row->character3_id, $row->character4_id, $row->character5_id ); $testArray = array(); foreach ($ids as $id) { if($id !== "0") { $this->db->select('character_name'); $this->db->from('characters'); $this->db->where('id', $id); $query = $this->db->get(); $row = $query->row(); $testArray[] = $row->character_name; } else { $testArray[] = "TBA"; } } return $testArray; } Hey Everybody, I am writing a SUPER SIMPLE script and for some reason I cannot figure this issue out. I guess I'm too close to the situation and have spent too many hours staring at this script. Here's the problem: I am running a basic SQL query through php that should return multiple rows of data and instead returns the first row multiple times. I'm not sure what the problem is, but I'm sure YOU can help! <?php //Get Invoice Rows $sql = 'SELECT * FROM timecard WHERE INVOICE_ID=\'1000\''; $result = mysql_query($sql); $rows = mysql_fetch_array($result); $num = mysql_num_rows($result); //Build Current Invoice $i=0; $invoice = '<table class="invoice" cellspacing="0" cellpadding="0">'; $invoice .= '<tr class="heading"><td>#</td><td>Invoice</td><td>Date</td><td>Time In</td><td>Time Out</td><td>Hours</td><td>$/Hr</td><td>Sub Total</td></tr>'; while($i < $num){ if( $i%2 ) { $eo = 'odd'; } else { $eo = 'even'; } $invoice .= '<tr id="invoiceRow" class="'.$eo.'"><td>'.$rows[0].'</td><td>PHG'.$rows[1].'</td><td>'.$rows[2].', '.$rows[4].' '.$rows[3].', '.$rows[5].'</td><td>'.$rows[6].'</td><td>'.$rows[7].'</td><td>'.$rows[8].'</td><td>'.$rows[9].'</td><td>'.$rows[10].'</td></tr>'; $runningTotal[$i] = $rows[10]; $i++; } //Get Total $total = array_sum($runningTotal); $invoice .= '<tr><td colspan="7" style="background-color: #000000; color: #ffffff; font-weight: bold; padding-left: 5px;">Total</td><td align="right" style="background-color: #333333; font-weight: bold; color: #FFFFFF; padding-right: 5px;">'.$total.'</td>'; $invoice .= '</table>'; echo $invoice; ?> Much thanks in advance for anyone that is able to resolve this problem, even just a try is nice!! Thank You, E Just finished a search script. However, when type two keywords it will return duplicate entries: Code: [Select] elseif(isset($_GET['search'])){ $search=$_POST['search']; $search=str_replace(" ", ".", $search); header("Location: ./index.php?q=".$search); } elseif(isset($_GET['q'])){ $search=$_GET['q']; $keywords=explode(".",$search); $sql10000="SELECT product_id FROM $tbl_name2 WHERE keyword LIKE '%" . implode("%' OR keyword LIKE '%",$keywords) . "%'"; $result10000=mysql_query($sql10000); if(mysql_num_rows($result10000)==0){ $content='<div class="center">Search found no results.</div>'; } else{ while($row10000=mysql_fetch_array($result10000)){ $product_id3=$row10000['product_id']; $sql15000="SELECT * FROM $tbl_name WHERE product_id=".$product_id3; $result15000=mysql_query($sql15000); while($row15000=mysql_fetch_array($result15000)){ extract($row15000); $content.=$product_name; } } } } I have 3 products: Test2 - microphone Test3 - audio, microphone Test123 - audio When you search "audio" you get: Test3, Test123 When you search "microphone" you get: Test2, Test3 When you search "audio microphone" you get: Test2, Test3, Test3, Test123 with Test3 being a duplicate. Is there anyway to correct this? I tried SELECT DISTINCT * FROM, but there's no difference in the results returned, from what I have now. Hello folks, I've got a problem with a search script. It's searching a db containing various properties (as in buildings) and it's not quite returning the correct results. The search form asks that you select a house type (4 options, all of which are tick boxes) and then the last part of the form is select how many bedrooms you'd like (which is a drop-down list featuring numbers 2-5) What should happen is someone selects one or more of the tick boxes and then the number of bedrooms and it returns all the house types that were ticked but only those with the number of bedrooms that were specified in the original search. Currently the results are correct in that they're showing the correct house types, but the number of bedrooms isn't right. e.g. if you chose 2 bedrooms in the search it shows those, as well as 3, 4 and 5 bedrooms in the results. Can't figure it out but it will be something to do with && and OR in my search script. Can anyone suggest a tweak to this that might work? (I'm using the $_GET function because the search form is in a Flash movie) $Result = mysql_query("select * from property_names where TownHouse = '$_GET[TownHouse]' OR Apartment = '$_GET[Apartment]' OR Detached = '$_GET[Detached]' OR SemiDetached = '$_GET[SemiDetached]' && visible= 'Yes' && bedrooms = '$_GET[Bedrooms]' && bedrooms = '$_GET[Bedrooms]'") When using cURL, how would I be able to include a call inside my get_all that basically will loop through all the next_page, get and store the data and then output it to $response->data when the "next_page" parameter becomes null? **Here is the method**: public function get_all() { return $response->data; } **This is what $response->data is returning as of now** (The cURL code wasn't included here): "paginator": { "total": 3092, "per_page": 500, "current_page": 2, "last_page": 7, "prev_page": "https://oc.com/api/v1/employees/?page=1", "next_page": "https://oc.com/api/v1/employees/?page=3" }, "data": [ { "id": 1592, etc.... Here are all of my unsuccessful attempts: public function get_all() { // $next_url = $response->paginator->next_page; // // foreach ($response as $next => $next_page) { // print_r2($next); // // if ($next_url !== null) { // $next_page = $response->data; // } // } // foreach ($response as $paginator => $next_page) { // if ($next_url !== null) { // $return[] = $response->data; // } // } // var_dump($response->paginator); // if ($next_url !== null) { // $this->get_all($path, $args, $next_url); // } return $response->data; } Edited October 30, 2019 by Sema314 Hi all, I am new to PHP and am trying to implement a window that opens when a user is trying to validate an organisation on our site. I have an initial page where users can enter data. One of the fields is organisations. This has a button to its right that lets the user search existing organisations in the mysql db. I have the search piece thanks to some code I found and altered. However, instead of a static non-linked list 1,2,3 coming back from the search, I need the search results to be links / or at least "select"-able. When the user chooses the organisation they were referring to that exists in the db I would like the selection to go back to the original php page and populate the organisation field. Ideally without having other data in the original form being lost. Any tips, hints or links would be greatly appreciated. Here is my code: <?php $dbHost = 'localhost'; $dbUser = 'root'; $dbPass = 'mypass'; $dbDatabase = 'mydb'; $con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error()); mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error()); // Set up our error check and result check array $error = array(); $results = array(); // First check if a form was submitted. // Since this is a search we will use $_GET if (isset($_GET['search'])) { $searchTerms = trim($_GET['search']); $searchTerms = strip_tags($searchTerms); // remove any html/javascript. if (strlen($searchTerms) < 3) { $error[] = "Search terms must be longer than 3 characters."; }else { $searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection. } // If there are no errors, lets get the search going. if (count($error) < 1) { $searchSQL = "SELECT Organisation_Name FROM vcaccount_contact_organisation WHERE "; // grab the search types. $types = array(); $types[] = isset($_GET['Organisation_Name'])?"`Organisation_Name` LIKE '%{$searchTermDB}%'":''; $types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked) if (count($types) < 1) $types[] = "`Organisation_Name` LIKE '%{$searchTermDB}%'"; // use the body as a default search if none are checked $andOr = isset($_GET['matchall'])?'AND':'OR'; $searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `Organisation_Name`"; // order by organisation. $searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}"); if (mysql_num_rows($searchResult) < 1) { $error[] = "The search term provided {$searchTerms} yielded no results."; }else { $results = array(); // the result array $i = 1; while ($row = mysql_fetch_assoc($searchResult)) { $results[] = "{$i}: {$row['Organisation_Name']}<br /><br />"; $i++; } } } } function removeEmpty($var) { return (!empty($var)); } ?> <html> <title>My Simple Search Form</title> <style type="text/css"> #error { color: red; } </style> <body> <?php echo (count($error) > 0)?"The following had errors:<br /><span id=\"error\">" . implode("<br />", $error) . "</span><br /><br />":""; ?> <form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" name="searchForm"> Organisation: <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /><br /> <input type="submit" name="submit" value="Search!" /> </form> <?php echo (count($results) > 0)?"Your search term: {$searchTerms} returned:<br /><br />" . implode("", $results):""; ?> </body> </html> SELECT i.item_id, i.title, i.price, i.p_and_p, SUM(i.price + i.p_and_p) AS `total_price`, i.listing, i.condition, i.start_date_time, i.listing_duration, CONVERT_TZ(DATE_ADD(i.start_date_time, INTERVAL concat(i.listing_duration) DAY), '+00:00', u.time_zone) AS `end_date_time` FROM items i LEFT JOIN sub_categories sc ON sc.sub_category_id = i.sub_category_id LEFT JOIN categories c ON c.name = 'test' JOIN users u WHERE u.username = 'Destramic' AND i.start_date_time < NOW() AND DATE_ADD(i.start_date_time, INTERVAL concat(i.listing_duration) DAY) >= NOW()I'm having a problem with my query returning more than 1 rows...I've even copied the row which is returning to see if that'll return 2 rows but it doesn't can anyone explain why this is happening please? Hello all,
Based on the suggestion of you wonderful folks here, I went away for a few days (to learn about PDO and Prepared Statements) in order to replace the MySQLi commands in my code. That's gone pretty well thus far...with me having learnt and successfully replaced most of my "bad" code with elegant, SQL-Injection-proof code (or so I hope).
The one-and-only problem I'm having (for now at least) is that I'm having trouble understanding how to execute an UPDATE query within the resultset of a SELECT query (using PDO and prepared statements, of course).
Let me explain (my scenario), and since a picture speaks a thousand words I've also inlcuded a screenshot to show you guys my setup:
In my table I have two columns (which are essentially flags i.e. Y/N), one for "items alreay purchased" and the other for "items to be purchased later". The first flag, if/when set ON (Y) will highlight row(s) in red...and the second flag will highlight row(s) in blue (when set ON).
I initially had four buttons, two each for setting the flags/columns to "Y", and another two to reverse the columns/flags to "N". That was when I had my delete functionality as a separate operation on a separate tab/list item, and that was fine.
Now that I've realized I can include both operations (update and delete) on just the one tab, I've also figured it would be better to pare down those four buttons (into just two), and set them up as a toggle feature i.e. if the value is currently "Y" then the button will set it to "N", and vice versa.
So, looking at my attached picture, if a person selects (using the checkboxes) the first four rows and clicks the first button (labeled "Toggle selected items as Purchased/Not Purchased") then the following must happen:
1. The purchased_flag for rows # 2 and 4 must be switched OFF (set to N)...so they will no longer be highlighted in red.
2. The purchased_flag for row # 3 must be switched ON (set to Y)...so that row will now be highlighted in red.
3. Nothing must be done to rows # 1 and 5 since: a) row 5 was not selected/checked to begin with, and b) row # 1 has its purchase_later_flag set ON (to Y), so it must be skipped over.
Looking at my code below, I'm guessing (and here's where I need the help) that there's something wrong in the code within the section that says "/*** loop through the results/collection of checked items ***/". I've probably made it more complex than it should be, and that's due to the fact that I have no idea what I'm doing (or rather, how I should be doing it), and this has driven me insane for the last 2 days...which prompted me to "throw in the towel" and seek the help of you very helpful and intellegent folks. BTW, I am a newbie at this, so if I could be provided the exact code, that would be most wonderful, and much highly appreciated.
Thanks to you folks, I'm feeling real good (with a great sense of achievement) after having come here and got the great advice to learn PDO and prepared statements.
Just this one nasty little hurdle is stopping me from getting to "end-of-job" on my very first WebApp. BTW, sorry about the long post...this is the best/only way I could clearly explaing my situation.
Cheers guys!
case "update-delete": if(isset($_POST['highlight-purchased'])) { // ****** Setup customized query to obtain only items that are checked ****** $sql = "SELECT * FROM shoplist WHERE"; for($i=0; $i < count($_POST['checkboxes']); $i++) { $sql=$sql . " idnumber=" . $_POST['checkboxes'][$i] . " or"; } $sql= rtrim($sql, "or"); $statement = $conn->prepare($sql); $statement->execute(); // *** fetch results for all checked items (1st query) *** // $result = $statement->fetchAll(); $statement->closeCursor(); // Setup query that will change the purchased flag to "N", if it's currently set to "Y" $sqlSetToN = "UPDATE shoplist SET purchased = 'N' WHERE purchased = 'Y'"; // Setup query that will change the purchased flag to "Y", if it's currently set to "N", "", or NULL $sqlSetToY = "UPDATE shoplist SET purchased = 'Y' WHERE purchased = 'N' OR purchased = '' OR purchased IS NULL"; $statementSetToN = $conn->prepare($sqlSetToN); $statementSetToY = $conn->prepare($sqlSetToY); /*** loop through the results/collection of checked items ***/ foreach($result as $row) { if ($row["purchased"] != "Y") { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToY = $statementSetToY->fetch(); foreach($resultSetToY as $row) { $statementSetToY->execute(); } } else { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToN = $statementSetToN->fetch(); foreach($resultSetToN as $row) { $statementSetToN->execute(); } } } break; }CRUD Queston.png 20.68KB 0 downloads Originally, I would get both, and unfortunately would inconsistently use both. Then, I wanted more consistently, so configured php.ini to only return objects as I felt accessing them was more concise. And then later, I found myself needing arrays more often, and initially would just typecast them to arrays but eventually my standard was to set the PDO's fetch style to an array. And now I find myself almost always explicitly requesting arrays and occasionally requesting columns or named values. Do you configure ATTR_DEFAULT_FETCH_MODE, and if so to what? PS. Anyone use FETCH_CLASS, FETCH_INTO or FETCH_NUM? If so, what would be a good use case? Moodle 2.5 *nix server Theme: Essential ---------------------- Hi Folks I have a small mind bender in how php is returning results from a mysql query. There are two issues: 1) The mysql query from phpmyadmin is correct, while the php function that handles the query from the website is not. 2) It takes a very long time to run this query with php, 30 seconds to over a minute. Phpmyadmin is rather quick (Query took 0.0239 seconds). The query is: SELECT u.firstname AS 'Name' , u.lastname AS 'Surname', c.shortname AS 'Course', ( CASE WHEN gi.itemname LIKE '%summative%' THEN 'SUMMATIVE' WHEN gi.itemname LIKE '%formative 2%' THEN 'FORMATIVE 2' ELSE 'MC' END) AS 'Assessment', from_unixtime(gi.timemodified, '%d/%m/%y') AS 'Date', IF (ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) > 70,'Yes' , 'No') AS Pass, ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) AS 'Mark', ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) AS 'Mark' FROM mdl_course AS c JOIN mdl_context AS ctx ON c.id = ctx.instanceid JOIN mdl_role_assignments AS ra ON ra.contextid = ctx.id JOIN mdl_user AS u ON u.id = ra.userid JOIN mdl_grade_grades AS gg ON gg.userid = u.id JOIN mdl_grade_items AS gi ON gi.id = gg.itemid JOIN mdl_course_categories AS cc ON cc.id = c.category WHERE gi.courseid = c.id AND gi.itemname != 'Attendance' AND u.firstname LIKE '%03%' AND gi.itemname LIKE '%mative%' ORDER BY `Name` , `Surname` , `Course`, `Assessment` ASCWhen I run the query in phpmyadmin , it gives back; Name Surname Category Module Course Assessment Date Competent Mark G03 Itumeleng Velmah Mokwa Fundamentals Communications CO1 119472 FORMATIVE 2 07/04/14 Yes 100.00 G03 Itumeleng Velmah Mokwa Fundamentals Communications CO1 119472 SUMMATIVE 07/04/14 Yes 100.00 G03 Itumeleng Velmah Mokwa Fundamentals Communications CO2 119457 FORMATIVE 2 05/04/14 Yes 100.00 G03 Itumeleng Velmah Mokwa Fundamentals Communications CO2 119457 SUMMATIVE 05/04/14 Yes 88.00 G03 Lally Sheila Mokane Fundamentals Communications CO1 119472 FORMATIVE 2 07/04/14 NYC 59.00 G03 Lally Sheila Mokane Fundamentals Communications CO1 119472 SUMMATIVE 07/04/14 Yes 90.00 G03 Lally Sheila Mokane Fundamentals Communications CO2 119457 FORMATIVE 2 05/04/14 Yes 100.00 G03 Lally Sheila Mokane Fundamentals Communications CO2 119457 SUMMATIVE 05/04/14 Yes 98.00And it is perfect so I have no issues with that. Now in php I call; function print_overview_table_groups($COURSE, $choosegroup, $fromdate, $todate, $numarray) { global $DB; //check data if(!$choosegroup){ die('No Records To Display.'); } $thisgroup = $numarray[$choosegroup]; $sql = "SELECT DISTINCT u.firstname AS 'Name' , u.lastname AS 'Surname', (CASE WHEN cc.parent = '2' THEN 'Fundamentals' WHEN cc.parent = '3' THEN 'Core' WHEN cc.parent = '4' THEN 'Elective' END) AS 'Category', cc.name AS 'Module', c.shortname AS 'Course', (CASE WHEN gi.itemname LIKE '%summative%' THEN 'SUMMATIVE' WHEN gi.itemname LIKE '%formative 2%' THEN 'FORMATIVE 2' ELSE 'MC' END) AS 'Assessment', from_unixtime(gi.timemodified, '%d/%m/%y') AS 'Date', IF (ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) > 70,'Yes' , 'NYC') AS Competent, ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) AS 'Mark' FROM mdl_course AS c JOIN mdl_context AS ctx ON c.id = ctx.instanceid JOIN mdl_role_assignments AS ra ON ra.contextid = ctx.id JOIN mdl_user AS u ON u.id = ra.userid JOIN mdl_grade_grades AS gg ON gg.userid = u.id JOIN mdl_grade_items AS gi ON gi.id = gg.itemid JOIN mdl_course_categories AS cc ON cc.id = c.category WHERE gi.courseid = c.id AND gi.itemname != 'Attendance' AND u.firstname LIKE '%03%' AND gi.itemname LIKE '%mative%' ORDER BY `Name` , `Surname` , `Course`, `Assessment` ASC"; return $DB->get_records_sql($sql); }This is returned to the index.php page from the function call; $lists = print_overview_table_groups($COURSE, $choosegroup, $fromdate, $todate, $numarray); print "<pre>"; print_r($lists); print "</pre>";The result is baffling... Array ( [G03 Itumeleng] => stdClass Object ( [name] => G03 Itumeleng [surname] => Mokwa [category] => Fundamentals [module] => Communications [course] => CO2 119457 [assessment] => SUMMATIVE [date] => 05/04/14 [pass] => Yes [mark] => 88.00 ) [G03 Lally] => stdClass Object ( [name] => G03 Lally [surname] => Mokane [category] => Fundamentals [module] => Communications [course] => CO2 119457 [assessment] => SUMMATIVE [date] => 05/04/14 [pass] => Yes [mark] => 98.00 ) )I only get one record for each student. Can anyone help me solve this? Regards Leon Ok, this may be just because I have been programming all day and my mind has gone blank (happens alot), but this is my PHP script: Code: [Select] <?php $query_distinct_item_types = mysql_query("SELECT DISTINCT name FROM item_types"); while($item_types = mysql_fetch_array($query_distinct_item_types)){ $distinct_item_types[] = $item_types['name']; } foreach($distinct_item_types as $item){ $query_item_total = mysql_query("SELECT item_type, SUM(price) WHERE item_type='$item' FROM costs GROUP BY item_type"); while($item_total = mysql_fetch_array($query_total_price)){ $item_totals[] = $item_total['SUM(price)']; } } $item_summery = $item_totals; ?> $item_summery which is = to $item_totals is returning null, any idea's? I am currently trying to make a baseball database with player statistics for each particular game. The page as of now looks something like this: Opponent #1 Player #1 Player #2 Player #7 Opponent #2 Player #1 Player #2 Player #5 and this goes on. When I click on Player #1 under Opponent #1 I get the correct stats. However when I click on Player #1 under Opponent #2 I get the same stats as if I was clicking Player #1 under Opponent #1. Here is the coding for the content page: Code: [Select] <?php require_once("includes/functions.php"); ?> <?php if (isset($_GET['gm'])) { $sel_gm = get_game_by_id($_GET['gm']); $sel_player = NULL; } elseif (isset($_GET['player'])) { $sel_gm = NULL; $sel_player = get_player_by_id($_GET['player'], $sel_gm); } else { $sel_gm = NULL; $sel_player = NULL; } ?> <?php include("includes/header.php"); ?> <table id="structure"> <tr> <td id="navigation"> <ul class="subjects"> <?php $game_set = get_all_games(); while ($game = mysql_fetch_array($game_set)) { echo "<li"; if ($game["Game_ID"] == $sel_gm) { echo " class=\"selected\""; } echo "><a href=\"content.php?gm=" . urlencode($game["Game_ID"]) . "\">{$game["Opponent"]}</a></li>"; $player_set = get_players_for_game($game["Game_ID"]); echo "<ul class=\"pages\">"; while ($player = mysql_fetch_array($player_set)){ echo "<li"; if ($player["Player_ID"] == $sel_player) { echo " class=\"selected\""; } echo "><a href=\"content.php?player=" . urlencode($player["Player_ID"]) . "\">{$player["First"]}" . " " . "{$player["Last"]}</a></li>"; } echo "</ul>"; } ?> </ul> </td> <td id="page"> <?php if (!is_null($sel_gm)) { // game selected ?> <h2><?php echo $sel_gm['Opponent']; ?></h2> <?php echo $sel_gm['Game_ID']; ?> <?php } elseif (!is_null($sel_player)) { // player selected ?> <h2><?php echo "{$sel_player['First']}" . " " . "{$sel_player['Last']}"; ?></h2> <div class="page-content"> <h3><?php echo $sel_player['Opponent']. "<br />" . " " ?></h3> <?php echo "PA: " . $sel_player['PA'] . "<br />" . " AB: " . $sel_player['AB']. "<br />" . " H: " . $sel_player['H'] . "<br />" . " HR: " . $sel_player['HR']. "<br />" . " RBI: " . $sel_player['RBI'] . "<br />" . " BB: " . $sel_player['BB']. "<br />" . " Runs: " . $sel_player['Runs'] . "<br />" . " SAC: " . $sel_player['SAC']. "<br />" . " ROE: " . $sel_player['ROE'] . "<br />" . " 1b: " . $sel_player['1b']. "<br />" . " 2b: " . $sel_player['2b'] . "<br />" . " 3b: " . $sel_player['3b']. "<br />" . " TB: " . $sel_player['TB'] . "<br />" . " SO: " . $sel_player['SO']. "<br />" . " GIDP: " . $sel_player['GIDP'] . "<br />" . " SB: " . $sel_player['SB']. "<br />" . " CS: " . $sel_player['CS']; ?> </div> <?php } else { // nothing selected ?> <h2>Select a game or player to edit</h2> <?php } ?> </td> </tr> </table> <?php require("includes/footer.php"); ?> And Here is the coding for the functions: Code: [Select] <?php function confirm_query($result_set) { if (!$result_set) { die("Database query failed:" . mysql_error()); } } function get_all_games() { global $connection; $query = "SELECT * "; $query .= "FROM offense "; $query .= "LEFT JOIN players ON offense.Player_ID = players.Player_ID "; $query .= "LEFT JOIN game ON offense.Game_ID = game.Game_ID "; $query .= "ORDER BY players.Player_ID ASC "; $query .= "LIMIT 1"; $game_set = mysql_query($query, $connection); confirm_query($game_set); return $game_set; } function get_players_for_game($Game_ID) { global $connection; $query = "SELECT players.*, offense.* FROM players INNER JOIN offense ON players.Player_ID = offense.Player_ID WHERE Game_ID = {$Game_ID} ORDER BY players.Player_ID ASC"; $player_set = mysql_query($query, $connection); confirm_query($player_set); return $player_set; } function get_game_by_id($Game_ID) { global $connection; $query = "SELECT game.*, offense.* "; $query .= "FROM game "; $query .= "INNER JOIN offense ON game.Game_ID = offense.Game_ID "; $query .= "WHERE offense.Game_ID=" . $Game_ID . " "; $query .= "LIMIT 1"; $result_set = mysql_query($query, $connection); confirm_query($result_set); if($game = mysql_fetch_array($result_set)) { return $game; } else { return NULL; } } function get_player_by_id($sel_player, $sel_gm) { global $connection; $query = "SELECT * "; $query .= "FROM offense "; $query .= "INNER JOIN players ON offense.Player_ID = players.Player_ID "; $query .= "INNER JOIN game ON offense.Game_ID = game.Game_ID "; $query .= "WHERE offense.Player_ID =" . $sel_player . " "; $query .= "AND offense.Game_ID =" . $sel_gm . " "; $query .= "ORDER BY players.Player_ID ASC "; $query .= "LIMIT 1"; $result_set = mysql_query($query, $connection); confirm_query($result_set); if($player = mysql_fetch_array($result_set)) { return $player; } else { return NULL; } } ?> My 5 tables in my database a defense: Player_ID, Game_ID, (this also has all of the stats for defense) game: Game_ID, Opponent, Game_Date offense: Player_ID, Game_ID, (this also has all of the stats for offense) pitching: Player_ID, Game_ID, (this also has all of the stats for pitching) players: Player_ID, First, Last Any help would be greatly appreciated. Thank You Hey freaks! I have a problem, i can't figure out how to recieve one single string from the database, i tried alot of things. Code: [Select] public function getpass($name){ $q = sprintf("SELECT password FROM database WHERE name='%s'", mysql_real_escape_string($name)); $result = mysql_query($q) or die(mysql_error()); // And here i tried every single way to fetch the data. Wich one should i use when its only one slot in a row i need? } I hope you can help me! |