PHP - Mysqli Query Problem
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; } } } Similar TutorialsHello,
Got a code, need to insert a query for displaying links of posts in section. Category is 'blog', each post has it's 'id', and 'subject', which should be a name for link, such as "blog.php?p='id'".
<!doctype html> <html lang="en"> <head> </head> <body class="base"> <div class="container"> <!-- PRZETWARZANIE WYNIKÓW Z BAZY --> <?php $total_pages = $link->query('SELECT * FROM news WHERE category="blog"')->num_rows; $page = isset($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1; $num_results_on_page = 1; if ($stmt = $link->prepare('SELECT * FROM news WHERE category="blog" ORDER BY date DESC LIMIT ?,?')) { $calc_page = ($page - 1) * $num_results_on_page; $stmt->bind_param('ii', $calc_page, $num_results_on_page); $stmt->execute(); $result = $stmt->get_result(); } while ($row = $result->fetch_assoc()): $text = $row['news']; $text = str_replace('[video]','<div class="video-container">',$text); $text = str_replace('[/video]','</div>',$text); $text = str_replace('[media]','',$text); $text = str_replace('[/media]','',$text); $embera = new \Embera\Embera(); echo '<div class="container"> <div class="row">'; ?> <div class="col-sm-4"> /* here is a place for links to published posts */ </div> <?php echo '<div class="col-sm-8"><h3>'.$row['subject'].'</h3>'; echo '<div class="tresc embed-responsive">'; echo $embera->autoEmbed($text); echo '</div></div> </div> </div>'; endwhile; ?> <!-- KONIEC PRZETWARZANIA WYNIKÓW Z BAZY --> <hr class="pagination_divider"> <center> <!-- PAGINATION --> <?php if (ceil($total_pages / $num_results_on_page) > 0): ?> <div class="sect_paginate"><ul class="pagination"> <?php if ($page > 1): ?> <li class="prev"><a href="blog.php?page=<?php echo $page-1 ?>">◂ WSTECZ</a></li> <?php endif; ?> <li class="currentpage"><a href="blog.php?page=<?php echo $page ?>"><?php echo $page ?></a></li> <?php if ($page < ceil($total_pages / $num_results_on_page)): ?> <li class="next"><a href="blog.php?page=<?php echo $page+1 ?>">DALEJ ▸</a></li> <?php endif; ?> </ul></div> <?php endif; $stmt->close(); ?> </center> <!-- END OF PAGINATION --> </div> </body> </html>
Hi, I am having problems returning values from a select statement. When I query directly in the databse, I get back the information I am looking for. I use an includes file for the database connection and my page shows that the connection was successful. Here is my code: Code: [Select] <?php $search = $_GET['searchFor']; $words = explode(" ", $search); $phrase = implode("%' AND articlename LIKE '%", $words); $sql ="SELECT * FROM articles WHERE articlename LIKE '%phrase%'"; $result =$conn->query($sql) or die('Sorry, could not get any articles at this time'); $row =($result->fetch_all()) or die('No records found'); $numRows =$result->num_rows; If($numRows==0) { echo "<h2>Sorry, no articles were found with '$search' in them.</h2>"; } else { While($row=$result->fetch_assoc()) { $articleid = $row['articleid']; $title = $row['articlename']; $shortdesc = $row['shortdesc']; echo "<h2>Search Results</h2><br><br>\n"; echo "<a href=\"index.php?content=showarticle&id=$articleid\">$title</a><br>\n"; echo "$shortdesc<br><br>\n"; } } ?> The search term is coming from a search form in the navigation. I have used "echo" statements to check and make sure that the sesrch word is coming through to tghe page containing the above code. I have tried mysqli_error() statements in several places and don't see where the problem is. When I try the search the message that comes back is "No records found" Does not makee sense because I know it is there, can find it, and even have the same syntax as the SELECT statement I use when I ask for the php code. Going crazy trying to sort this out. Any suggestions, help etc are greatly appreciated. Thank youi. I have a function that performs a SELECT query on a MySQL database and populates the results in an array of Class. At the moment it is using PDO. Trouble is that PDO is not supported by the server the code will run on. Changing server is not an option, nor is installing PDO.
I have tried splitting the function to use the PDO method if installed or MySQLi if not. I am struggling to get the MySQLi part working though. Can anyone help me with this?
Here is the function I have so far which basically returns nothing from the MySQLi part:
public function mysqlSelectToClass($query, $className, $args = NULL) { include (dirname(__FILE__) . "/../config.php"); if (class_exists('PDO')) { $db = new PDO('mysql:host=' . $db_host . ';dbname=' . $db_name . ';charset=utf8', $db_user, $db_pass); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbQuery = $db->prepare($query); if (isset($args)) { foreach ($args as $arg) { $dbQuery->bindParam(array_values($arg)[0], array_values($arg)[0], PDO::PARAM_STR); } } $dbQuery->execute(); return $dbQuery->fetchAll(PDO::FETCH_CLASS, $className); } else { $db = mysqli_connect($db_host, $db_user, $db_pass, $db_name); $dbQuery = $db->prepare($query); if (isset($args)) { // Type is a string of parameter types e.g. "is" $type = array_values($args)[0]; // Params is an array of parameters e.g. array(1, 'value') $params = array_values($args)[1]; call_user_func_array('mysqli_stmt_bind_param', array_merge(array($dbQuery, $type), $this->byrefValues($params))); $result = mysqli_stmt_execute($dbQuery); mysqli_close($db); } elseif ($dbResult = mysqli_query($db, $query)) { $result = mysqli_fetch_object($dbResult, $className); mysqli_close($db); } return $result; } }the byrefValues function is simply swapping a value array to a reference array and seems to be working fine. I can paste that too if required. Thanks Jay Edited by jay20aiii, 24 September 2014 - 12:41 PM. Hi,
So I'm not very familiar with using mySQLi, but I'm wanting to print a user's last name, depending on which user is logged in (obviously it needs to be their last name and not another users)
So, we're getting the session for the user and saving their username as $username
$user = Session::Get('current_user'); $username = $user->Get('username');And then my query to display their lastname? $result = $db->Select('lastname')->Where('username', '$username')->Get(Config::Get('db.table')); print_r($result)But the query doesn't work, no error? Forgive my ignorance! >.< Hello there, I'm new to this site/forum so i dont know if this is the right forum to post a code review / commentary request .... I have a function that handels the sql code... Know i would like to know what you think off it ? can I do something different or better ?.. Code: [Select] <?PHP /* * Private function db_query($sql) | handle.... * whit checking en extendid error reporting.... * Runs a query but does not return a result array.... * @String $sql | this is the sql query you whant to run..... */ private function db_query($sql) { $this->sql = $sql; switch ( DEBUG_QUERY ) { // check debug mode... case true: try { // probeer query uit te voeren... $handle = $this->query($this->sql); if(!$handle) // if error whit the query... { $this->rollback(); throw new Exception('MySQLi Query went wrong error ==> ' . mysqli::$error); } } catch (Exception $e) { // error afhandeling and reporting.. echo '<hr />'; echo '<span style="color:red"><b>A MySQLi Query went wrong:</b></span><br />'; echo var_dump($e->getMessage()); echo '<br />'; echo nl2br($e->getTraceAsString()); echo '<br />'; echo 'Error in File: ' . $e->getFile(); echo '<br />'; echo 'Thrown Exception on line: ' . $e->getLine(); echo '<br /><hr />'; exit(); } // end error afhandeling and reporting... break; case false: $handle = $this->query($this->sql); break; } // end switch... return $handle; } /* * Public function db_Do | handels the insert, update, select and delete query's * A lot off optional options for the different query's * @String $type | Choose between the four type's | select, insert, update or delete | Default is Select * @String $table | Select witch table you whant to use | give a vailid tablename you whant to use in the query * @String $values | Input the values uw whant to select from the table | * for all - row1, row2, row3 | id, username, password * @String $where | The where operator for the query | Where $where = | give a vailid row name | if used you must fill in the other two where operators | default = empty (optional) * @String $opparator | The operator for the where operator | =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * | whit check in_array | where 2 | default = empty (optional) * @String / Int $where_val | The where value for the where operator | WHERE $where{id} $opparator{=} $where_val{1} | where 3 | default = empty (optional) * @Bool $use_and | if TRUE you can use the AND operator | linked to the other three and operators | if you use 1 you must fill in all 4 of them | default = false (optional) * @String $and_key | Value for the AND operator | same as $order_by | AND $and_key{username} | and 2 | default = empty (optional) * @String $and_oparetor | The operator for the and section | same as $opparator | =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * | whit check in_array | and 3 | default = '=' (optional) * @String $and_value | The value for by the and_key | same as $where_val | AND $and_key{username} $and_oparetor{=} $and_value{'jhon'} | and 4 | default = empty (optional) * @String $order_by | value for the Order by operator only used if hase a value | ORDER BY $order_by{id} | if used you must alsow fill in the second order by operator | default = empty (optional) * @String $order_key | Value for the Order key by the order value | ORDER BY $order_by{id} $order_key{asc, desc} | check in_array | default = asc (optional) * Error msg and checks includid, Failsafe... * Runs the query and returns a row.... * Uses the db_query function... * Version 1.0.0 */ public function db_Do($type = 'select', $table, $values, $where = NULL, $opparator = NULL, $where_val = NULL, $use_and = FALSE, $and_key = NULL, $and_oparetor = '=', $and_value = NULL, $order_by = NULL, $order_key = 'ASC') { switch ( DEBUG_QUERY ) { // check debug mode... case true: if(in_array($type, $this->SQL_TYPE, TRUE)) { // check for correct $type... if(in_array($order_key, $this->ORDER_KEY, TRUE)) { // check if order key is allowd $order_key.... if(in_array($opparator, $this->OPARATORS, TRUE)) { // check for vallid oparetors... if(empty($table) or strlen($table) >= 4) { // check if $table correct is.... if(empty($values) or strlen($values) >= 4) { // check if the $values are given correctly.... if(in_array($and_oparetor, $this->OPARATORS, TRUE)) { // check if and oparetor is allowd..... switch( $type ) { // witch type... case 'select': // Build the SQL Query.... $query = 'SELECT '. $this->real_escape_string($values) .' FROM '. $table .' '; if(!empty($where) and (empty($where_val) or empty($opparator))) { $row = 'Sorry you have to fill in all 3 of the where conditions!'; return $row; } elseif(!empty($where) || !empty($where_val) || !empty($opparator)) { $query .= 'WHERE '. $where .' '. $opparator .' "'. $this->real_escape_string($where_val) .'" '; } if($use_and == true and !empty($and_key) and !empty($and_value)) { $query .= 'AND '. $and_key .' '. $and_oparetor .' "'. $this->real_escape_string($and_value) .'" '; } elseif($use_and == true and (empty($and_key) or empty($and_value))) { $row = 'Sorry you have to fill in all 3 off the AND oparetors correctly.'; return $row; } if(!empty($order_by)) { $query .= ' ORDER BY '. $order_by .' '. $order_key .''; } $this->sql = $query; $handle = $this->db_query($this->sql); $row = $handle->fetch_assoc(); mysqli_free_result($handle); break; case 'insert': // Build the SQL Query...... $query = 'INSERT INTO '. $table .' ('. $this->real_escape_string($values) .') '; $query .= 'VALUES ('. $this->real_escape_string($where) .')'; $this->sql = $query; $handle = $this->db_query($this->sql); $row = ($handle) ? true : false; unset($handle); // empty / unset $handle... break; case 'update': // Build the SQL Query...... $query = 'UPDATE '. $table .' '; $query .= 'SET '. $this->real_escape_string($values) .' '; if(!empty($where) and !empty($where_val) and !empty($opparator)) { $query .= 'WHERE '. $where .' '. $opparator .' "'. $this->real_escape_string($where_val) .'" '; } elseif(empty($where) or empty($where_val) or empty($opparator)) { $row = 'Sorry you have to fill in all 3 of the where conditions!'; return $row; } if($use_and == true and !empty($and_key) and !empty($and_value)) { $query .= 'AND '. $and_key .' '. $and_oparetor .' "'. $this->real_escape_string($and_value) .'" '; } elseif($use_and == true and (empty($and_key) or empty($and_value))) { $row = 'Sorry you have to fill in all 3 off the AND oparetors correctly.'; return $row; } $this->sql = $query; $handle = $this->db_query($this->sql); $row = ($handle) ? true : false; unset($handle); // empty / unset $handle.... break; case 'delete': //Construct the delete query..... $query = 'DELETE FROM '. $table .' '; $query .= 'WHERE '. $where .' '. $opparator .' "'. $this->real_escape_string($where_val) .'" '; if($use_and == true and !empty($and_key) and !empty($and_value)) { $query .= 'AND '. $and_key .' '. $and_oparetor .' "'. $this->real_escape_string($and_value) .'" '; } elseif($use_and == true and (empty($and_key) or empty($and_value))) { $row = 'Sorry you have to fill in all 3 off the AND oparetors correctly.'; return $row; } $this->sql = $query; $handle = $this->db_query($this->sql); $row = ($handle) ? true : false; unset($handle); // empty / unset $handle.... break; } // end switch( $type )..... } else { // Correct Oparetors...... $row = 'Incorrect Oparetor in the AND section choose out: =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * or use the FreeQuery'; } } else { // Correct VALUES..... $row = 'Sorry you have to fill in the values parameter correctly and it hase to be bigger then 3 chars.'; } } else { // Correct TABLE.... $row = 'Sorry you have to fill in the table parameter correctly and it hase to be bigger than 3 chars.'; } } else { // Correct Oparetors...... $row = 'Incorrect Oparetor in the WHERE section choose out: =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * or use the FreeQuery'; } } else { // if order_key is NOT allowd.... $row = 'Incorrect Order by opparator: <b>'. $order_key .'</b> choos between (asc or desc)'; } } else { // if not correct type return error msg.... $row = 'Incorrect type: <b>'. $type . '</b> choose between (select, insert, update or delete)'; } break; // end case true... case false: break; // end case false... } // end switch( debug_query )... return $row; } // end public function db_Do()..... ?> It's still a work in process so it's not done yet... Hi,
I can I include a date range criteria to query with in the following code? The date field in the table (t_persons) is IncidentDate.
$criteria = array('FamilyName', 'FirstName', 'OtherNames', 'NRCNo', 'PassportNo', 'Gender', 'IncidenceCountryID', 'Status', 'OffenceKeyword', 'AgencyID', 'CountryID', 'IncidenceCountryID' ); $likes = ""; $url_criteria = ''; foreach ( $criteria AS $criterion ) { if ( ! empty($_POST[$criterion]) ) { $value = ($_POST[$criterion]); $likes .= " AND `$criterion` LIKE '%$value%'"; $url_criteria .= '&'.$criterion.'='.htmlentities($_POST[$criterion]); } elseif ( ! empty($_GET[$criterion]) ) { $value = mysql_real_escape_string($_GET[$criterion]); $likes .= " AND `$criterion` LIKE '%$value%'"; $url_criteria .= '&'.$criterion.'='.htmlentities($_GET[$criterion]); } //var_dump($likes); } $sql = "SELECT * FROM t_persons WHERE PersonID>0" . $likes . " ORDER BY PersonID DESC";Kind regards. Hi ! I am trying to translate my mysqli count query that works perfectly into prepared statements. Unfortunately, after playing around and using my knowledge of PS, I have come up with this script which fails to execute and returns a http 500 error. I may have missed something very silly, I require some guidance on fixing the error.
<?php $conn = mysqli_connect("xxxx", "xxxx", "xxxx", "xxx"); $sel_query = "SELECT S1, B1 COUNT(IF(S1 = ?, 1, NULL)) 'Accepted', COUNT(IF(S1 = ?, 1, NULL)) 'Rejected', COUNT(IF(S1 = ?, 1, NULL)) 'Under_Review' FROM Enrol"; $stmt = $conn->prepare($sel_query); $Accepted="Accepted"; $Rejected="Rejected"; $Under_Review="Under Review"; $stmt->bind_param("sss",$Accepted, $Rejected, $Under_Review); $stmt->execute(); $result = $stmt->get_result(); // get the mysqli result if($result->num_rows === 0) exit('No records found!'); while($row = $result->fetch_assoc()) { ?> <tr> <td><?php echo $row["Accepted"]; ?></td> <td><?php echo $row["Rejected"]; ?></td> <td><?php echo $row["Under_Review"]; ?></td> </tr> </table>
Edited June 24, 2020 by PythonHelp Hello everyone! I am trying to insert a student into a table (with TIMESTAMP; works with VARCHAR, not TIMESTAMP). Can anyone help?
Variable
$time_stamp = date("D M j G:i:s T Y");Populate DB Query ("DROP TABLE IF EXISTS enrolled") || !$link->query("CREATE TABLE enrolled(course_id VARCHAR(50), student_id VARCHAR(50), user_ip VARCHAR(50), time_stamp TIMESTAMP(6))Insert Query INSERT INTO enrolled(course_id,student_id,user_ip,time_stamp) VALUES('$course','$number','$user_ip','$time_stamp') Edited by MatthewPatten, 12 December 2014 - 08:32 AM.
$start = 0; 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 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); ?> 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. 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(); } <?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 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 im joining a table onto the query to show how many likes a post has but it is displaying the post x amount of times depending on how many likes there are. I think its something to do with the way im joining onto the pid of the post table: $post_query = $link->query("SELECT p.*, u.*, l.* FROM ".TBL_PREFIX."posts as p JOIN ".TBL_PREFIX."users as u ON (u.u_username = p.p_poster) LEFT JOIN ".TBL_PREFIX."post_likes as l ON (l.l_pid = p.p_pid) WHERE p_tid = '$tid' ORDER BY p.p_time_posted ASC")or die(print_link_error()); $likes = array(); while($post_info = $post_query->fetch()) { // SOF LIKE LIST if (count($post_info['l_pid']) >= 1) { $likes[] = $post_info['l_username']; $amount_likes = count($likes); $slice = array_slice($likes, 0, 4, true); $remain = array_slice($likes, 4, $amount_likes, true); $remain_num = count($remain); $like_list = ''; if($amount_likes > 4) { for($i=0; $i<=3; $i++) { $like_list .= profile_link($likes[$i]).', '; } $like_list .= 'and '.$remain_num.' other like this'; } elseif($amount_likes <= 3) { for($i=0; $i<3; $i++) { $like_list .= profile_link($likes[$i]).' '; } $like_list .= 'like this'; } } the likes are stored in their own database table seperate from the posts any advice? <form method="post" > <fieldset> <table> <tr> <td>naam van het gerecht:</td> <td><input type="text" name="nieuwgerecht" /></td> </tr> <tr> <td></td> <td></td> <td>ingredient 1:<input type="text" name="ingredient1" /></td> </tr> <tr> <td></td> <td></td> <td>ingredient 2:<input type="text" name="ingredient2" /></td> </tr> <tr> <td></td> <td></td> <td>ingredient 3:<input type="text" name="ingredient3" /></td> </tr> <tr> <td></td> <td></td> <td>ingredient 4:<input type="text" name="ingredient4" /></td> </tr> <tr> <td></td> <td></td> <td>ingredient 5:<input type="text" name="ingredient5" /></td> </tr> </table> <input type="submit" name="cmdvoegtoe" value="voeg toe" /> </fieldset> </form> <?php if(isset($_POST['cmdvoegtoe'])) { if (empty($_POST['ingredient1'])) { echo "<script>alert(\"ingredient nummer 1 moet zeker ingevuld zijn!\");</script>"; } else { $query="INSERT INTO tblgerecht VALUES(NULL, '$_POST[nieuwgerecht]')"; mysql_query($query, $connectie) or die('Error, insert query failed'); } } ?> Parse error: parse error in ... on line 118 problem with mysql query can someone help me with it I have a running total that I am pulling from a database that I need to sort by year. I have tried adding WHERE YEAR(datepicker) = '2015' but keep getting an error. Here is the original query that works fine when I run it. Just don't need all the records.
SELECT id, datepicker, startmiles, endmiles, O.totalMiles, car, section, (select sum(totalMiles) FROM vehicle WHERE id <= O.id) 'runningTotal' FROM vehicle O ORDER BY datepicker DESC Hi Im just working on a wordpress pugin at the moment and Iw as trying out this piece of code $mylink = $wpdb->get_row("SELECT * FROM $wpdb->testtable WHERE id = 1"); echo $mylink->id ; there is data in the table there is an id equal to one but it not coming up with anything I tried it with anouther pable and it works fine I can for example $mylink = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE id = 1"); echo $mylink->post_content ; That comes up fine with the data But the first one I dont know why its not working can anyone help Thanks James Having some odd issues with a simple query :S. The first problem is that i have selected all records but it miss's out records in a pattern (the first, fifth, ninth and so on). The second issue is i am trying to select by ascending order but it's just not doing it. The QUERY Code: [Select] $comments = "SELECT * FROM $commentsTable LIMIT $start, $per_page "; $commentResults = mysql_query($comments); $commentRows = mysql_fetch_array($commentResults); The while loop displaying the records Code: [Select] <?php while($commentRows = mysql_fetch_array($commentResults)){?> <div id="comments"> <div id="CommentWrapper"> <div id="comment"> <div id="UserName"><? echo $commentRows['id']." "; ?><? echo $commentRows['name'];?></div> <div id="UserComment"><? echo $commentRows['comment'];?></div> <div id="UserEmail"><a href="<? echo $commentRows['email'];?>"><? echo $commentRows['email'];?></a></div> <div id="PostDateTime"><i>Posted: </i><? echo $commentRows['datatime'];?></div> </div> </div> </div> <?php } mysql_close(); ?> http://dvplus.webuda.com/oophptest/database.query.php <<< the project |