PHP - Using The Mysqli Object Fetch_assoc() Problem...
I've been starting to play around the mysqli class and I've been having trouble using it due to various error it gives me from simple queries like this one. I'm not sure what the error is really, I've been following the php manual. Any help would be greatly appreciated.
Code: [Select] <?php $mysqli = new MySQLi('localhost', 'root', 'root', 'jaipai'); if ($mysqli->connect_errno) { echo "There was a connection error: ". $mysqli->connecterrno; } class testClass { private $db; function __construct($mysqli) { $this->db = $mysqli; } public function pageInfo() { $query = "SELECT * FROM users WHERE username = jaipai"; $results = $this->db->query($query); $result = $this->db->fetch_assoc($results); return $result['username']; } } $testClass = new testClass($mysqli); echo $testClass->pageInfo(); ?> This gives me this error: Code: [Select] Fatal error: Call to undefined method mysqli::fetch_assoc() in /Users/JPFoster/Sites/Research & Development/Programs/Object Sandbox/DatabaseConnection.php on line 30 Just to be a little more informative I've also tried this method Code: [Select] $results = $this->db->query($query); $result = $results->fetch_assoc(); return $result['username']; This gives me an error: Code: [Select] Fatal error: Call to a member function fetch_assoc() on a non-object in Sites/Research & Development/Programs/Object Sandbox/DatabaseConnection.php on line 30 I'm not sure which is on the best path to go. Any help would be greatly appreciated. Similar TutorialsRandom Error that im getting on my webhost, not localhost. Fatal error: Call to a member function fetch_assoc() on a non-object in /home/*****/index.php on line 127 Line 127: while ($premium = $row->fetch_assoc()) { Code: <div class="toplist-content"> <table cellspacing="0"> <tbody> <?php $row = $home->getList(1); while ($premium = $row->fetch_assoc()) { ?> <tr class="table"> <td class="name"><a href="server.html"> <h3> <?php echo ucfirst($premium['servername']); ?> </a> <font size='1.5'><?php echo ucfirst(substr($premium['serverdesc'],0,25)). "..."; ?> </h3> </font> </td> <td class="revision"><h3> <?php echo ucFirst($premium['revision']); ?> </h3></td> <td class="votes"><h3> <?php echo $premium['vote']; ?> </h3></td> <td class="status"><?php if($home->getStatus($premium['host'], $premium['port']) == true) { echo "<span class='ticket open'>Online</span>"; } else { echo "<span class='ticket closed'>Offline</span>"; } ?> </td> </tr> <?php } ?> </tbody> </table> </div> The getList() function : function getList($premium) { $query = $this->con->query("SELECT * FROM `".$this->prefix."servers` WHERE `premium` = '".$premium."' && `ban` = '0' ORDER BY (SELECT COUNT(*) FROM `".$this->prefix."votes` WHERE `serverId` = '".$this->prefix."servers.id') DESC") or die(mysqli_error()); return $query; } Hi all, I'm getting the following error, but I cannot see why: ERROR: Fatal error: Call to a member function fetch_assoc() on a non-object in {filepath} on line 36 CODE: Code: [Select] <?php ini_set('display_errors',1); error_reporting(E_ALL); require_once("aconfig.php"); $eid = $_GET["event"]; echo '<html> <head> <title>Admin Control Panel :: PRINT TICKETS</title> <style type="text/css"> body { font-family: Helvetica, Arial; } </style> </head> <body>'; //start classes $db = new db(); //connect to DB //attempt it $sql = new mysqli(db::$config['host'], db::$config['user'], db::$config['pass'], db::$config['db']); //check for ERR if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } // if($eid == "edit"){ echo '<h1>SELECT EVENT</h1> <p>Select an event to print tickets for</p> <p>'; $query = 'SELECT * from `tickets` ORDER by id'; $query = $sql->real_escape_string($query); // Perform Query $result = $sql->query($query); // Loop Through Result while ($row = $result->fetch_assoc()) { echo '− <a href="ptickets.php?event='.$row[id].'">'.$row[event_name].'</a> <br />'; } echo '</p>'; }else { $query2 = 'SELECT * from `orders` WHERE `id` = '.$eid.', paid = "1"'; $query2 = $sql->real_escape_string($query2); // Perform Query $result2 = $sql->query($query2); // Loop Through Result while ($row2 = $result2->fetch_assoc()) { echo '<table cellspacing="1" cellpadding="1" border="1" width="400"> <tbody> <tr> <td colspan="2"><strong>Online Ticket</strong></td> </tr> <tr> <td width="300"> <p>Event: <strong>'.$row2[eventname].'</strong></p> <p>Holder Name: <strong>'.$row2[name].'</strong></p> <p>No. Adult tickets: <strong>'.$row2[adult_tix].'</strong><br /> No. Concession tickets: <strong>'.$row2[concess_tix].'</strong></p> </td> <td> <p><u>STAFF</u></p> <p><em>Rip this side off once ticket holder has entered.</em></p> </td> </tr> </tbody> </table> <p> </p>'; } } echo '</body></html>'; ?> What the script does: if the page is ?event=edit, it lists all the available events. If not, it checks what event id is at ?event and lists that ID from the DB. What's wrong with it? Thanks Ever since I started using OOP this past week, I have not been able to go back to the old "procedural" methods. HOwever, I seem to be stuck on creating a mysql connection that I can reuse in all of my classes. After I set up a connection to mysql using the mysqli object, I am unable to use the mysqli in other objects. Code: [Select] $mysqli = new mysqli(.....); class new_class { function quickQuery () { $mysqli->query('some query') } } Obviously, this doesn't work, because $mysqli is not defined within that functions scope. One way, is to use global keyword. Code: [Select] global $mysqli However, globals "are the root of all evil" and simply go against the idea of encapsulation in OOP. What's a way around this? HOWEVER: 1) I still want to use the mysqli object 2) I don't want to reference the $link of the db each time I instantiate a new class .... Maybe I'm asking too much? And I've google for the past hour or so. Singleton seems interesting but it requires the creation of a new db connection class. I want to use the mysqli object. I am getting an error when the clear banned ip over 15mins script runs if there is a row to remove from the database, what am I doing wrong here and the error is Quote PHP Fatal error: Call to a member function fetch_object() on a non-object in /path/to/file/index.php on line 14 Code: [Select] <?php // clear banned ip over 15mins $timeBAN = time(); $sql = $link->query("SELECT unban, id FROM attempts WHERE unban <= '$timeBAN'"); if ($sql->num_rows > 0) { while ($result = $sql->fetch_object()) { //<----THIS IS LINE 14 CAUSING ERROR if there is data $remove=$result->id; $sql = $link->query("DELETE FROM attempts WHERE id='$remove'"); } $sql->close(); } // check if user banned $sql = $link->query("SELECT ip, unban FROM attempts WHERE ip='$ip'"); if ($sql->num_rows > 0) { $result = $sql->fetch_object(); $unban = $result->unban; $timeCHECK = $unban-$timeBAN; if ($timeCHECK > 0 ) { $remain = round($timeCHECK/60); } $sql->close(); } // reset the auto_increment of attempts $sql = $link->query("SELECT id FROM attempts"); if ($sql->num_rows == 0) { $sql = $link->query("ALTER TABLE attempts AUTO_INCREMENT = 1"); } ?> Hello
I am still fairly new to the PDO / mysqli thing and I would really appreciate some help with escaping special characters from the below code.
$sth = ("SELECT * from table WHERE field1 = '$bob' and field2 != ''"); foreach ($dbh->query($sth) as $row) { $who = $row['field2']; $why = $row['field1']; $dbh1->query("UPDATE table SET who = '$who', date = '$row[DATE]', time = '$row[TIME]' WHERE field1 = '$why'")or die(mysqli_error($db)); }I have tried using the prepared statement as well as the mysqli_real_escape_string but sees the code results as an object. Any help or comments would be greatly appreciated. I am trying to build an object-oriented interface for a website. My classes include a "Database" class with a constructor method that connects to a database and a destructor method that disconnects from the database, a child class called "Content" that will display content stored in the database, another child class called "User" that handles registration, updating user info, logging in, and logging out, etc., and a "Validator" class that will validate all forms. So far I have the database class, the content class, and the index.php page started. My problem is that I cannot get the data returned from the function (using mysqli prepared statements) to display on the main page. I have read tutorials using MySQL, but I am using MySQLi with prepared statements. Any help is appreciated. Code: [Select] Database.php /* The Database class handles connecting to and disconnecting from the database. All interaction with the database is then extended from this class. The constructor will be run automatically each time a new instance of the Database class (or one of its child classes) is made. */ abstract class Database { // assign variables to use in the constructor private $host = 'localhost'; private $user = ''; private $password = ''; private $database = ''; // define constructor method to connect to database public function __construct() { $this->connect = new mysqli($this->host, $this->user, $this->password, $this->database); // if the connection failed kill the script and display an error if($this->connect->connect_errno) { die('Critical database error: ' . $this->database->error . '. Please contact a site administrator.'); } } // define destructor method to disconnect from the database public function __destruct() { $this->connect->close(); } } Content.php require_once('Database.php'); /* This class will display all website content that is held in the database. Anything that is stored in the database that needs to be shown on the front end of the website will go through this class. */ class Content extends Database { public function pageInfo($page) { $query = $this->connect->prepare('SELECT pageTitle, pageHeading, pageContent FROM pageInfo WHERE pageName = ?'); $query->bind_param('s', $page); $query->execute(); $query->bind_result($title, $heading, $content); return $query->fetch(); // procedurally this returns the values of the bound variables which then I can use just by typing echo $variableName // if i echo the variables out inside this method, they display at the top of index.php // how do i call them into my variables to display where i want // return $query->fetch(); should return that object to main script but then how do i call those values } public function displayUsers() { } public function searchUsers() { } } index.php <?php $page = 'index.php'; require_once('modules/Content.php'); $page = new Content(); list($title, $heading, $content) = $page->pageInfo('index.php'); ?> <!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> <title><?php echo $title; ?></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="includes/style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="scripts/cufon-yui.js"></script> <script type="text/javascript" src="scripts/arial.js"></script> <script type="text/javascript" src="scripts/cuf_run.js"></script> </head> <body> <!--begin main--> <div class="main"> <?php include('header.php'); ?> <?php include('menu.php'); ?> <!--begin content--> <div class="content"> <!--begin content_resize--> <div class="content_resize"> <!--begin mainbar--> <div class="mainbar"> <!--begin article--> <div class="article"> <h2><span><?php echo $heading; ?></span></h2> <div class="clr"></div> <p><?php echo $content; ?></p> </div> <!--end article--> </div> <!--end mainbar--> <?php include('sidebar.php'); ?> <div class="clr"></div> </div> <!--end content_resize--> </div> <!--end content--> <?php include('footer.php'); ?> </div> <!--end main--> </body> </html> I don't know why it won't work.. as the topic titles says that I am trying to pass a mysqli object to a property in another class but it keeps me getting an error.
here's the code for the mysqli object that i want to pass to another class
class ConnectMe2Db { public $dbname = 'somedatabase'; public $dbuname = 'root'; public $dbpass = ''; public $dbhost = 'localhost'; function __construct() { $mysqli = new mysqli($this->dbhost,$this->dbuname,$this->dbpass,$this->dbname) or die ('ERROR: '.$mysqli->connect_errno); return $mysqli; } # OTHER CODES... }and here is the class that i want the Mysqli object to pass to: class DatabaseUsers { private $dbconnection; function __construct() { $this->dbconnection = new ConnectMe2Db();#mysqli object will be passed to this attribute '$dbconnection' } public function session($username, $password) { $UserName = mysqli_real_escape_string($this->dbconnection,$username); $Password = mysqli_real_escape_string($this->dbconnection,md5($password)); $querry = "SELECT * FROM trakingsystem.login WHERE username='$username' and password='$password'"; $result = mysqli_query($this->dbconnection,$querry) or die (mysqli_error($this->dbconnection)); $count = mysqli_num_rows($result); $row = mysqli_fetch_array($result); if ($count > 0) { #some code here } } #some other code here }and this outputs 4 errors: #outputs 2 of these: Warning: mysqli_real_escape_string() expects parameter 1 to be mysqliand some mysqli_query() expects parameter 1 to be mysqli mysqli_error() expects parameter 1 to be mysqliis there something wrong with the logic that I've made? please help thanks Hi I'm trying to insert unique info retrieved to my database but seems like I'm doing something wrong with my quary my current setup is as follow
mxit.php
<?php $con=mysqli_connect("*****","*******","*******","******"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_close($con); ?> <? define('TIMEZONE', 'Africa/Harare'); date_default_timezone_set(TIMEZONE); $ip = $_SERVER["REMOTE_ADDR"]; $post_time = date("U"); $mxitua = $_SERVER["HTTP_X_DEVICE_USER_AGENT"]; $mxitcont = $_SERVER["HTTP_X_MXIT_CONTACT"]; $mxituid = $_SERVER["HTTP_X_MXIT_USERID_R"]; $mxitid = $_SERVER["HTTP_X_MXIT_ID_R"]; $mxitlogin = $_SERVER["HTTP_X_MXIT_LOGIN"]; $mxitnick = $_SERVER["HTTP_X_MXIT_NICK"]; $mxitloc = $_SERVER["HTTP_X_MXIT_LOCATION"]; $mxitprof = $_SERVER["HTTP_X_MXIT_PROFILE"]; if(!isset($mxitid)) { $mxitid = "DEFAULT"; } mysqli_query($con,"INSERT INTO mxit (ip,time,user_agent,contact,userid,id,login,nick,location,profile) VALUES ($ip,$post_time,$mxitua,$mxitcont,$mxituid,$mxitid,$mxitlogin,$mxitnick,$mxitloc,$mxitprof)"); mysqli_close($con); ?> hi What is the correct way to do a function like: Code: [Select] public function check_($db, $skills) { $arr_tags = array('16', '17', '36', '546'); $z = implode(', ', array_fill(0, count($arr_tags), '?')); $str = implode('', array_fill(0, count($arr_tags),'s')); $par = "'" . implode("','", $arr_tags) . "'"; $c_arr_tags = count($arr_tag); $sql = $db -> prepare(" SELECT offer_id_offer FROM offer_has_tags WHERE tags_id_tags IN ($z) GROUP BY offer_id_offer HAVING COUNT(*) = ? "); $sql -> bind_param("$srt.'i'", $par, $c_arr_tags); $sql -> execute(); $sql -> bind_result($id_offer); return $id_offer; } At the moment i got: Number of elements in type definition string doesn't match number of bind variables Hello guys, i'm currently building my own cms, a personal project, and now im stucked on an error "Call to a member function query() on a non-object in.. please help
after creating this function.. I know the db connection and everything else worked out because i have a similar function that works just without the switch or the numrow if statement.
protected function _pageStatus($option, $id){ //check if page exists, if it does return the status, or return 404 switch($option){ case 'alpha' : $sql = "SELECT status FROM pages WHERE nick = '$id'"; break; case 'num' : $sql = "SELECT status FROM pages WHERE id = '$id'"; break; } if($result = $this->_db->query($sql)){ //<--- THE ERROR WAS ON THIS LINE. if($result->num_rows > 0){ while ($status = $result->fetch_object()) { return $status; } return $status; $result->close(); } else { return 404; } } } Hi I have an infuriating problem which is stalling me with two large projects for a well known NGO right now. I am using mysqli and bound variables where the number of variables to bind is dependent on user input. I have a version of the code below working in php 5.2 but as of php 5.3 this method is no longer valid, specifically due to a change in the behavior of call_user_func_array with bound variables as arrays. I have read about this problem eslewhere but cannot get any of the workarounds to work with my example. Any help would be greatly appreciated. Code: [Select] # $parts is an array with variable number of values # $type is an array with variable number of values # $params is an array with variable number of values $query = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT taxon.TaxonID, FROM taxon WHERE . join('', $parts) . " ORDER BY taxon.TaxonID"; # Prepare stmt if ($stmt = $mysqli->prepare($query)) { call_user_func_array (array($stmt, 'bind_param'),array_merge(array(join('', $type)), $params)); # execute $stmt->execute(); # bug info echo $stmt->errno, ':', $stmt->error; #store result $stmt->store_result(); # bind results $stmt->bind_result($ID); # fetch values while ($stmt->fetch()) { # results code goes here! } # free memory $stmt->free_result(); # close statement $stmt->close(); } Hi all,
I have a query that return data into the array $row with values, but $id from the first line of the while stay null. Why? $con = oci_connect("xxx", "xxx", "xxx"); $query = "SELECT id, name from table_web WHERE record_module='AA' and parent_id='".$parentId."'"; $stid=oci_parse($con, $query); oci_execute($stid); while($value = oci_fetch_assoc($stid)) { $id = $value['id']; $row[$id]['id'] = $value['id']; $row[$id]['name'] = $value['name']; } return $row;
The following snippit should retrieve 10 images stored in an SQLite database table. But for some reason that mystifies me, it only retrieves 9. (Or one less than the number of images that are actually stored on the table):
___________
# retrieve photos for this property $query = "SELECT * FROM binary_data where propID = $prop_id"; $result = $db->query($query); $row = $result->fetch(PDO::FETCH_ASSOC); # save each image data to file foreach($result as $row) { $filename = $row['filename']; $image = $row['bin_data']; file_put_contents($filename, $image); } ?> _____________ It saves the ones it gets to the temporary files as it should, and they appear on the webpage as they should. But one is always missing. Any suggestions/corrections appreciated. -Robert <?php if (isset($_POST['reset-submit'])) { $selector = $_POST['selector']; $validator = $_POST['validator']; $password = $_POST['password']; $password2 = $_POST['password2']; // probably better to check this earlier if (empty($password) || empty($password2)) { header("Location: ../create-new-password.php?newpassword=empty&selector=$selector&validator=$validator"); } elseif ($password !== $password2) { header("Location: ../create-new-password.php?newpassword=passwordsnotmatch"); } $currentDate = date("U"); require "dbh.inc.php"; $sql = "SELECT * FROM reset_password WHERE selector=? AND expires >= $currentDate"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { echo "SQL error 1"; exit(); } else { mysqli_stmt_bind_param($stmt, 'ss', $selector, $currentDate); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if (!$row = mysqli_fetch_assoc($result)) { echo 'You need to re-submit your reset request.'; exit(); } else { $tokenBin = hex2bin($validator); $tokenCheck = password_verify($tokenBin, $row['token']); if (!$tokenCheck) { echo 'You need to re-submit your reset request.'; exit(); } else { $email = $row['email']; $sql = "SELECT * FROM users WHERE email = $email"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { echo "SQL error 2"; exit(); } else { mysqli_stmt_bind_param($stmt, 's', $email); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if (!$row = mysqli_fetch_assoc($result)) { echo "SQL error 3"; exit(); } else { $sql = "UPDATE users SET password=? WHERE email=?"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { echo "SQL error4 "; exit(); } else { $hashed_password = password_hash($password, PASSWORD_DEFAULT); mysqli_stmt_bind_param($stmt, 'ss', $hashed_password, $email); mysqli_stmt_execute($stmt); $sql = 'DELETE FROM reset_password WHERE email=?'; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { echo 'SQL error5'; exit(); } else { mysqli_stmt_bind_param($stmt, 's', $email); mysqli_stmt_execute($stmt); header("Location: ../signup.php?newpassword=updated"); } } } } } } } mysqli_stmt_close($stmt); mysqli_close($conn); header('Location: ../reset-password.php?reset=success'); } else { header('Location: ../index.php'); } I always get this errors:
Warning: mysqli_stmt_bind_param(): Number of variables doesn't match number of parameters in prepared statement in C:\xampp\htdocs\php_login_system-master\includes\reset-password.inc.php on line 26
But i dont find the mistake in the Code. Can someone help me please Hi,
In my code i am fetching row per row out of my database through
->fetch(PDO::FETCH_ASSOC)this fetch have i put in a WHILE loop to fetch all the rows, one at a time while($select_rma_row = $select_rma_detail->fetch(PDO::FETCH_ASSOC)){In my array $select_rma_row there are a lot of value's that are (int) 1 and i really want to echo them as "YES" (1 = YES) What is the best way to change every (int) 1 to "YES" in that array? also is there a whay i can call every $key inside that array? Like you do with a foreach i.e. : if $select_rma_row[$key] == 1 { $select_rma_row[$key] == "YES"; }Thank you! Edited by Raz3rt, 21 May 2014 - 09:30 AM. hi guys I have two functions and they work well, but now i have a problem in the last if the email is sent like www.yoursite.com/reset_password.php?userid=0&code= and not http://your.url/set_new_password.php?userid=564979&code=54c4a2767c2f485185ab72cdcf03ab59 so, the problem is that i can get the value of hash and the userid. If i do an echo "$hash" in the function code(); it shows the value like 564979&code=54c4a2767c2f485185ab72cdcf03ab59 my question is, how i can do the same in the last if? above two functions. Same occur in the last select select userid from password_reset where code=? none userid is showed, it is always zero. Code: [Select] <? function check($sql, $db, $email) { if(!empty($_POST['email'])) { $email = $_POST["email"]; if ($sql = $db->prepare("select email from users where email=?")) { $sql->bind_param('s', $email); $sql->execute(); $sql->bind_result($email); if ($sql->fetch()) { return true; } else { return false; } } } } function code($sql, $db, $hash, $pwdHasher, $userExists, $sendPass) { if (check($sql, $db, $email)) { $pwdHasher = new PasswordHash(8, FALSE); $hash = $pwdHasher->HashPassword($userExists["email"]); $sendPass=$hash; ($sql = $db->prepare('insert into password_reset (code) values (?)')); $sql->bind_param('s', $hash); $sql->execute(); $sql->fetch(); return true; } } if (code($sql, $db, $hash, $pwdHasher, $userExists, $sendPass)) { ($sql = $db->prepare("select userid from password_reset where code=?")); $sql->bind_param('s', $hash); $sql->execute(); $sql->bind_result($hash); $sql->fetch(); echo $hash; $pwrurl = "www.yoursite.com/reset_password.php?userid=" .$hash . "&code=" . $sendPass; $mailbody = "Dear user,<br><br>If this e-mail does not apply to you please ignore it. It appears that you have requested a password reset at our website www.yoursitehere.com<br> To reset your password, please click the link below. If you cannot click it, please paste it into your web browser's address bar.<br> <a href='$pwrurl'>$pwrurl</a> <br> <br> Thanks,\nThe Administration"; $mail->MsgHTML($mailbody); $mail->AddAddress($email,"Membro"); $mail->IsHTML(true); if(!$mail->Send()) { echo "Deu erro: " . $mail->ErrorInfo; } else { echo "Enviado com sucesso"; } $sql->close(); $db->close(); } ?> any help? thanks Ok, this is rather bizarre. First this code... if($postCount > 0) { $i = 0; while($row = $this->db->fetch_assoc($post_pagination->resource())) { // echo $row['post_message']; $content .= ($i % 2 == 0 ? '<tr class="odd">' : '<tr>'); $content .= '<table>'; $content .= '<tr><td>'.$row['username'].'</td></tr>'; $content .= '<tr>'; $content .= '<td><p>'.$row['post_message'].'</p></td>'; $content .= '</tr>'; $content .= '</table>'; $content .= '</tr>'; $i++; } $content .= '<tr><td>| '.$plinks.' |</td></tr>'; } For whatever reason, if I comment out the line with $row['post_message'] everything works as expected. If I leave that in there like it is now, I get a completely blank white page. I've also tried assigning it to a variable within the loop like... $post_message = $row['post_message']; and that works fine, until I try echo'ing it then the same blank white page result. I've double checked the query, both in PHP and in PHPMyAdmin and it is working correctly. Here's the query code: $post_pagination = new pagination($ppg, "SELECT `posts`.`post_id`, `posts`.`post_message`, `cg_accounts`.`id`, `cg_accounts`.`username` FROM `".$this->dbname."`.`threads`, `".$this->dbname."`.`posts` INNER JOIN `crikeyga_central`.`cg_accounts` ON (`cg_accounts`.`id` = `posts`.`userid`) WHERE `posts`.`thread_id`=`threads`.`thread_id` AND `posts`.`thread_id`='".$thread_id."' ORDER BY `posts`.`post_timestamp` ASC"); I've also double checked the pagination class is working as expected, and it's fine in every other page it's used in. Also $ppg is the correct value(simply holds the current page number). $this->dbname is also correct, and as mentioned above the query works in PHPMyAdmin. And $post_pagination->resource() is holding the correct value and I've checked the database class in particular $this->db->fetch_assoc() and that's working fine. Really not having much luck pinning this one down, no errors are coming up(error reporting(E_ALL)). seems strange to me that $row['username'] comes up fine, but $row['post_message'] results in a white page. The values are also what they should be. Any help is appreciated! Thanks, Ace
Hi everyone, Happy New Year in advance! I have the following error occurring :- while ($row = $query_result->fetch_assoc()) { $result[] = $row; } Which is in this query :- public function DbGetAll($queryString) { $query_result = $this->db->query($queryString); $result = array(); while ($row = $query_result->fetch_assoc()) { $result[] = $row; } return $result; }
I'm guessing it's a problem with the sql query but I'm not sure how to fix? The error log also references this file :- Hey, I'm wondering what the issue is, I'm new to using PDO and objects so I'm sure this is a common error but setting me on the right track would be greatly appreciated. Code: [Select] Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND password = d41d8cd98f00b204e9800998ecf8427e' at line 1' in /Users/JPFoster/Sites/Jaipai.Blog/engine.php:47 Stack trace: #0 /Users/JPFoster/Sites/Jaipai.Blog/engine.php(47): PDO->query('SELECT * FROM u...') #1 /Users/JPFoster/Sites/Jaipai.Blog/index.php(7): SiteEngine->login('', '') #2 {main} thrown in /Users/JPFoster/Sites/Jaipai.Blog/engine.php on line 47 Code: [Select] public function login($user, $pw){ $user = addslashes($this->user); $pw = md5($pw); $query = "SELECT * FROM users WHERE username = ".$user." AND password = ".$pw; //set up query $results = $this->pdo->query($query); $num_rows = $results->num_rows; if ($num_rows == 1){ $row = $results->fetch_assoc(); echo "Worked!"; //$this->set_session($row['id'], $row['username'], $row['email']); } else { echo "Your Username and Password did not match"; } //if user + passs match { redirect (member page) and set up sessions // Else ... Retry... } } I don't see an issue with my query, and the object is instantiated by having the submit button isset() and i use login($_post[user], $_post[pw]) For convenience and efficiency purposes I'm changing my MySQL database to store PHP Objects as opposed to tons of individuals variables. In converting the user/login system I've come across a really weird problem. I can register a new user to the site, but only the first one in the database will work. I can register others and they get put in the database correctly, but for some reason the app doesn't see them or even recognize that they exist. Only the first entry in the database will work as it's supposed to. For instance, if I drop the first database entry, the second one (now first) will begin to work. In most cases, I'm pulling all Object entries from the database and looping through them with foreach() to find the specific one I want. I've just come off of an 8 hour coding spree and my brain is just shot at the moment. I really think I just need a new pair of eyes. I'm sure that it's something simple, but I can't see it atm. I'm attaching the User class file which handles login, registration, and anything that I think would be affecting this. Thanks for the help. |