PHP - Trouble Returning Mysql Results
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 Similar TutorialsMy 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; } 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 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. Greetings 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. 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]'") 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>"; } ?> 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> Hi Folks, I'm thinking this is simple, but just can't seem to figure it out. I use similar code for different tables that works fine, but for this table, it doesn't work so I'm thinking this is a MySQL issue. Here's the code: Code: [Select] $sqlmeds = mysql_query("SELECT ALL value FROM test WHERE type like 'media:'"); $meds = mysql_fetch_array($sqlmeds); foreach ($meds as $med){ echo "$med"; } and here is the relevant area of the table with row names "type" and "value" type value . . . media: painting media: works on paper media: collage/assemblage . . . When I run the query to find all 3 values from within phpMyAdmin, no problem, all three are returned, but when I run the exact same query from php, I only get "painting" returned, and oddly, I get an array with two values in it, both of which are "painting". Any ideas??? Thanks!! p.s. I also tried this just in case instead of the foreach, but same result: Code: [Select] for ($i=0; isset($meds[$i]); ++$i) { echo "$meds[$i]"; } I'm having trouble getting all of the results out of a query array, as it is I only get the first result and nothing else. Here's the basic code I'm working with: Code: [Select] $query = "SELECT data_txt FROM jos_servicedirectory_fields_data WHERE fieldid = 19 AND itemid = $item->itemid"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ $listtags = $row['data_txt']; $tags = "$listtags, "; $title = "<div class='servicedirectoryItemTitle'><table class=\"sdlistingitemtitle\" cellspacing=\"5\"><tbody><tr>$listingimage<td style=\"vertical-align:top;width:690px;\">$listingbasicicon<span class=\"$listingtitleclass\">$listinglogo<a href=\"{$href}\" {$onClick} title=\"{$item->title}\">{$item->title}</a></span><br /><span class=\"listingdescription\">$listingdescription</span></td><td style=\"vertical-align:top;\">$featuredribbon$moreinfobasic</td></tr></tbody></table><div class=\"listingbottom\">Tags:<span class=\"listingtags\"> $tags </span></div></div>"; } I've also tried using a foreach loop thinking that would pop all of the results but I end up not getting anything at all then. I'm guessing I'm setting the foreach loop up wrong. Here's how I'm trying to do it: Code: [Select] foreach($listtags as $value) { $tags = $value; } Does it have something to do with sticking the $tags variable in the $title variable? I wouldn't think that would matter, but the strange thing is I use this exact same query in a different part of this component and just echo it directly and it works fine. 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? 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 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 I am new to php, I am trying to capture the url and place into a variable but I only get the 1st digit to show, I just cant see what I am doing wrong. Sorry to ask such a basic question but I just can't work it out, I have attached a screen shot of all me code, your help would be very very much appreciated. Hey everyone. So I am coding a badge system for my website usersystem. I am trying to think how I'll handle issues before actually starting to code it and one issue I just can't seem to figure out how to handle.. How would I limit the amount of MySQL results to show per line. Eg. A user has 6 badges but I'd only like to show 2 per line. So in total it'd show 3 lines with 2 badges per line. If that makes any sense? Is there any way possible to actually do this? I'm working on a website that uses a database to display the employees from different states. Below is the code I'm using and everything works great, but I can't figure out why all the results are getting posted twice. I'm trying to isolate just one state so we can have a different contact page for each state. Thanks for any help! Please let me know if you need more information. (I'm attaching a screenshot of what's happening as well.) Code: [Select] <? include "public/public_common.php"; //Open Database Connection $db = open_db_connection(); $sql = "SELECT DISTINCT state_full = 'california' from users where active = 'Y' and show_on_contactus = 'Y'"; $results = mysql_query($sql, $db); if(!mysql_num_rows($results) == FALSE) { while($row = mysql_fetch_array($results, MYSQL_BOTH)) { echo "<ul id=\"directors\">\n"; $state_sql = "SELECT * from users where active = 'Y' and show_on_contactus = 'Y' and state_full = 'california' order by last_name"; $state_results = mysql_query($state_sql, $db); if(!mysql_num_rows($results) == FALSE) { while($state_row = mysql_fetch_array($state_results, MYSQL_BOTH)) { echo "<li>\n"; echo " <div class=\"fl dirimg\">\n"; if($state_row[photo] == "") { echo "<img border=\"0\" width=\"61\" height=\"85\" src=\"images/exe_placeholder.jpg\" alt=\"$state_row[first_name] $state_row[last_name]\" />\n"; } else { echo "<img border=\"0\" width=\"61\" height=\"85\" src=\"n2team/pictures/$state_row[photo]\" alt=\"$state_row[firstname] $state_row[last_name]\" />\n"; } echo " </div>\n"; echo " <span class=\"fr\">$state_row[first_name] $state_row[last_name]<br />\n"; echo " $state_row[title]<br />\n"; echo " $state_row[city], $state_row[state]<br />\n"; //echo " <a href=\"mailto:$state_row[email]\">$state_row[email]</a></span></li>\n"; } } echo "</ul>\n"; } } ?> Hello, This is query in MySQL Quote mysql> LOAD DATA LOCAL INFILE '/var/www/html/numbers.csv' INTO TABLE details FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (number); Query OK, 0 rows affected (0.00 sec) Records: 2200 Deleted: 0 Skipped: 1200 Warnings: 0 Now, I am trying to run the same query in PHP and display the same results.... (i.e. Records, Deleted, Skipped) Quote <?php $db=mysql_connect("localhost", "user", "1234") or die(mysql_error()); $dname="database"; mysql_select_db($dname)or die(mysql_error()); $sqlstatement="LOAD DATA LOCAL INFILE '/var/www/html/numbers.csv' INTO TABLE details FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (number)" ; mysql_query($sqlstatement) or die(mysql_error());; echo "it is done!"; ?> Tried mysql_fetch_array, row but could not get it to work... please help guys |