PHP - Query Returning No Values, But Works In Database
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 Similar TutorialsMoodle 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 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 Hi all, I'm looking for some pointers in regards to my form.. How would I firstly trim the $_POST value of the variables that come through via the form (I'm only using one for now)..I know I'm making a right dogs dinner of it. In my head I'm thinking, trim all the posts first before i even assign a variable to it ( i dont know if thats possible), then use an array for when more values start coming through via the form. You know as i make a contact form that requires more data from the user..
<?php require_once '../connection/dbconfig.php'; include_once('../connection/connectionz.php'); //get the values //Get the request method from the $_SERVER $requestType = $_SERVER['REQUEST_METHOD']; //this is what type //echo $requestType ; if($requestType == 'POST') { //now trim all $_POSTS $search_products = trim($_POST['search_products']); // if(empty($search_products)){ echo '<h4>You must type a word to search!</h4>'; }else{ $make = '<h4>No match found!</h4>'; $new_search_products = "%" . $search_products . "%"; $sql = "SELECT * FROM product WHERE name LIKE ?"; //prepared statement $stmt = mysqli_stmt_init($conDB); //prepare prepared statements if(!mysqli_stmt_prepare($stmt,$sql)) { echo "SQL Statement failed"; }else{ //bind parameters to the placeholder mysqli_stmt_bind_param($stmt, "s", $new_search_products ); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); echo'<h2> Search Result</h2>'; echo 'You searched for <strong><em>'. $search_products.'</em></strong>'; while($row = mysqli_fetch_assoc($result)){ echo '<h4> (ID : '.$row['pid']; echo ') Book Title : '.$row['name']; echo '</h4>'; } } } } ;?>
If any one can shed some light on this, or some pointers..that would be very nice... Thanks Darren
I have posted one set of values into my database and it worked fine but when i input another set they wont go inside unless i changes the value of the primary index colum. I want to be able to insert a new values regardless of the primary index value. Any idears...? 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 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]"; } Nothing is being returned. Why?
<?php error_reporting(E_ALL); ini_set("display_errors", 1); require("../PHPMailer/class.phpmailer.php"); include 'includes.php'; $mail = new PHPMailer; $subject = $_POST['subject']; $text = $_POST['newsletterBody']; $mail->IsSMTP(); // Set mailer to use SMTP $mail->Host = 'localhost'; // Specify main and backup server $mail->Port = '465'; $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = '**EMAIL_USERNAME**'; // SMTP username $mail->Password = '**EMAIL_PASSWORD**'; $mail->SMTPAuth = true; $mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted $mail->From = '**EMAIL_ADDRESS**'; $mail->FromName = '**EMAIL_NAME'; $email = getEmail("62", $DBH); foreach ($email as $newEmail) { $addEmail = $newEmail->email; $mail->AddAddress($addEmail); $DBH = null; $addEmail = ""; } $mail->AddReplyTo('**EMAIL_REPLY_TO**', '**EMAIL_REPLY_TO_NAME**'); $mail->WordWrap = 50; // Set word wrap to 50 characters $mail->IsHTML(true); // Set email format to HTML $mail->Subject = $subject; $mail->Body = $text; $mail->AltBody = $text; if(!$mail->Send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; exit; } $insertSql = "INSERT INTO newsletter_log (date, title, body) VALUES (?,?,?)"; $insertParams = array(time(), $subject, $text); $newsletterAdd = $DBH->prepare($insertSql); $newsletterAdd->execute($insertParams) echo 'Message has been sent <a href='newsletter.php'>Return back</a>"; ?>This is the include section that you need function getEmail($inId, $DBH) { if (!empty($inId)) { $blogstmt = $DBH->prepare("SELECT email_addr FROM newsletter_emails WHERE id = :userId"); $blogstmt->bindParam(":userId", $inId); $blogstmt->execute(); } else { $blogstmt = $DBH->prepare("SELECT * FROM newsletter_emails"); $blogstmt->execute(); } $postArray = array(); $results = $blogstmt->fetchAll(PDO::FETCH_ASSOC); foreach($results as $row){ $myPost = new nlEmails($row["id"], $row['email'], $DBH); array_push($postArray, $myPost); } return $postArray; $DBH = null; } class nlEmails { public $id; public $email; function __construct($inId=null, $inEmail=null, $DBH) { if(!empty($inId)) { $this->id = $inId; } if(!empty($inEmail)) { $this->email = $inEmail; } } }The database is created with the newsletter_emails "id", "first_name", "last_name", "email_addr". Thanks! Hi all, I am having some trouble with a script.. all works fine except for the calculation part. It isn't adding up, but the reason for this is because when I echoed all the variable it seems that they are blank, the problem is I can't figure out why? <?php # you don't display errors on in-use scripts, do you? ini_set('display_errors',0); error_reporting(E_ALL|E_STRICT); class webPoll { # makes some things more readable later const POLL = true; const VOTES = false; # number of pixels for 1% on display bars public $scale = 2; public $question = ''; public $answers = array(); private $header = '<form class="webPoll" method="post" action="%src%"> <input type="hidden" name="QID" value="%qid%" /> <h4>%question%</h4> <br /> <ul>'; private $center = ''; private $footer = "\n</ul>%button%\n</form>\n"; private $button = '<p class="buttons"><button type="submit">Vote!</button></p>'; private $md5 = ''; /** * --- * Takes an array containing the question and list of answers as an * argument. Creates the HTML for either the poll or the results depending * on if the user has already voted */ public function __construct($params) { $this->question = array_shift($params); $this->answers = $params; $this->md5 = md5($this->question); $this->header = str_replace('%src%', $_SERVER['SCRIPT_NAME'], $this->header); $this->header = str_replace('%qid%', $this->md5, $this->header); $this->header = str_replace('%question%', $this->question, $this->header); # seperate cookie for each individual poll isset($_COOKIE[$this->md5]) ? $this->poll(self::VOTES) : $this->poll(self::POLL); } private function poll($show_poll) { $replace = $show_poll ? $this->button : ''; $this->footer = str_replace('%button%', $replace, $this->footer); # static function doesn't have access to instance variable if(!$show_poll) { $results = webPoll::getData($this->md5); $votes = array_sum($results); } for( $x=0; $x<count($this->answers); $x++ ) { $this->center .= $show_poll ? $this->pollLine($x) : $this->voteLine($this->answers[$x],$results[$x],$votes); } echo $this->header, $this->center, $this->footer; } private function pollLine($x) { isset($this->answers[$x+1]) ? $class = 'bordered' : $class = ''; return " <li class='$class'> <label class='poll_active'> <input type='radio' name='AID' value='$x' /> {$this->answers[$x]} </label> </li> "; } private function voteLine($answer,$result,$votes) { echo "Answer: $answer"; echo "<br />"; echo "Result: $result"; echo "<br />"; echo "Votes: $votes"; echo "<br />"; echo "<br />"; $result = isset($result) ? $result : 0; $percent = round(($result/$votes)*100); $width = $percent * $this->scale; return " <li> <div class='result' style='width:{$width}px;'> </div>{$percent}% <label class='poll_results'> $answer </label> </li> "; } // remainder of script here ?> The ones that are returning blank a $result and $votes $results should be the number of votes a specific option has received while $votes is the total number of votes in the whole poll. My database contains the following data... QID AID votes 685b9628ca340529fa54208c65721dd7 2 205 685b9628ca340529fa54208c65721dd7 0 5 685b9628ca340529fa54208c65721dd7 1 2 It's from the following tutorial - http://net.tutsplus.com/tutorials/ph...poll-with-php/ Can anyone advise me here? Many thanks, Greens85 Im trying to understand the code below. (taken from an O'REILLY book) Im trying to get my head around this, so can anyone tell me if im thinking about this in the right way; The function (fix_names) borrows the values from $a1,$a2 and $a3 and puts them into $n1,$n2, and $n3. It then processes the strings contained within these newly created variables and then returns the processed values back into $a1,$a2,and $a3? The variables $n1,$n2, and $n3 cannot be echoed as they were created within the function.? Please correct me if im wrong. Code: [Select] <html> <head> </head> <body> <?php $a1 = "EDWARD"; $a2 = "thomas"; $a3 = "wriGHT"; fix_names($a1,$a2,$a3); echo $a1." ".$a2." ".$a3; function fix_names(&$n1,&$n2,&$n3) { $n1 = ucfirst(strtolower($n1)); $n2 = ucfirst(strtolower($n2)); $n3 = ucfirst(strtolower($n3)); } ?> </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? 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. 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? 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? Dear All Members here is my table data.. (4 Columns/1row in mysql table)
id order_no order_date miles How to split(miles) single column into (state, miles) two columns and output like following 5 columns /4rows in mysql using php code.
(5 Columns in mysql table) id order_no order_date state miles 310 001 02-15-2020 MI 108.53 310 001 02-15-2020 Oh 194.57 310 001 02-15-2020 PA 182.22
310 001 02-15-2020 WA 238.57 ------------------my php code -----------
<?php
if(isset($_POST["add"]))
$miles = explode("\r\n", $_POST["miles"]);
$query = $dbh->prepare($sql);
$lastInsertId = $dbh->lastInsertId(); if($query->execute()) {
$sql = "update tis_invoice set flag='1' where order_no=:order_no"; $query->execute();
} ----------------- my form code ------------------
<?php -- Can any one help how to correct my code..present nothing inserted on table
Thank You Edited February 8, 2020 by karthicbabuI'm trying to update every record where one field in a row is less than the other. The code gets each row i'm looking for and sets up the query right, I hope I combined the entire query into one string each query seperated by a ; so it's like UPDATE `table` SET field2= '1' WHERE field1= '1';UPDATE `table` SET field2= '1' WHERE field1= '2';UPDATE `table` SET field2= '1' WHERE field1= '3';UPDATE `table` SET field2= '1' WHERE field1= '4';UPDATE `table` SET field2= '1' WHERE field1= '5'; this executes properly if i run the query in phpMyAdmin, however when I run the query in PHP, it does nothing... Any advice? 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! 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 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>"; } ?> 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! after cloasing connection of database i still got the values form database. Code: [Select] <?php session_start(); /* * To change this template, choose Tools | Templates * and open the template in the editor. */ require_once '../database/db_connecting.php'; $dbname="sahansevena";//set database name $con= setConnections();//make connections use implemented methode in db_connectiong.php mysql_select_db($dbname, $con); //update the time and date of the admin table $update_time="update admin set last_logged_date =CURDATE(), last_log_time=CURTIME() where username='$uname'limit 3,4"; //my admin table contain 5 colums they are id, username,password, last_logged_date, last_log_time $link= mysql_query($update_time); // mysql_select_db($dbname, $link); //$con=mysql_connect('localhost', 'root','ijts'); $result="select * from admin where username='a'"; $result=mysql_query($result); mysql_close($con); //here i just check after closing data baseconnection whether i do get reselts but i do, why? echo "after the cnnection was closed"; if(!$result){ echo "cont fetch data"; }else{ $row= mysql_fetch_array($result); echo "id".$row[0]."usrname".$row[1]."passwped".$row[2]."date".$row[3]."time".$row[4]; } // echo "<html>"; //echo "<table border='1' cellspacing='1' cellpadding='2' align='center'>"; // echo "<thead>"; // echo"<tr>"; // echo "<th>"; // echo ID; // echo"</th>"; // echo" <th>";echo Username; echo"</th>"; // echo"<th>";echo Password; echo"</th>"; // echo"<th>";echo Last_logged_date; echo "</th>"; // echo "<th>";echo Last_logged_time; echo "</th>"; // echo" </tr>"; // echo" </thead>"; // echo" <tbody>"; //while($row= mysql_fetch_array($result,MYSQL_BOTH)){ // echo "<tr>"; // echo "<td>"; // echo $row[0]; // echo "</td>"; // echo "<td>"; // echo $row[1]; // echo "</td>"; // echo "<td>"; // echo $row[2]; // echo "</td>"; // echo "<td>"; // echo $row[3]; // echo "</td>"; // echo "<td>"; // echo $row[4]; // echo "</td>"; // echo "</tr>"; // } // echo" </tbody>"; // echo "</table>"; // echo "</html>"; session_destroy(); session_commit(); echo "session and database are closed but i still get values from doatabase session is destroyed".$_SESSION['admin']; ?> session is destroyed but database connection is not closed. thanks |