PHP - Trouble With Mysqli Query
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! >.< Similar TutorialsHi, I am having trouble coding for mysqli update. Please, somebody tell me the correct way. I'm trying to update the "lastused" (current date) field in "emailtbl". Somebody please tell the best way to code this. Below is the message and following, the current code: Fatal error: Call to undefined function curdate() in C:\xampp\htdocs\home\lastused.php on line 14 $db = new mysqli('localhost', 'root', 'pass', 'mydb'); if($db->connect_errno > 0) {die('Unable to connect to database [' . $db->connect_error . ']');} $sql = <<<SQL SELECT * FROM `emailtbl` WHERE `id` = '$id' SQL; if(!$result = $db->query($sql)) {die('There was an error running the query [' . $db->error . ']');} $lastused = $_POST['lastused']; $lastused = curdate(); echo "last date accessed is ".$data['lastused']; $result->free(); $db->escape_string('This is an unescape "string"'); $db->close(); ?> $update= mysqli_query($dbconnect, "UPDATE emailtbl SET lastused = curdate() WHERE id ='$id'"); if($update == false) { die("UPDATE FAILED: ".mysqli_error($dbconnect)); } echo "$lastused is the last date this account was accessed"; Hey all, I'm having some trouble running some mysql statements through mysqli. I've tried to debug them various ways, but to no avail. This is the offending code: class DBOPS { protected $config, $mysqli; public function __construct () { $this->config = array (...snip...); $this->mysqli = new mysqli ($this->config['server'], $this->config['username'], $this->config['password'], $this->config['database']); session_start(); } public function Login ($username, $password) { $toreturn = NULL; //Problem area is from here... $encryptedpassword = hash(...snip...); print_r(array( $this->config['usertable']['username'], $username, $this->config['usertable']['password'], $encryptedpassword)); $statement = $this->mysqli->stmt_init(); $statement->prepare('SELECT * FROM users WHERE ? = ? AND ? = ?'); $statement->bind_param( 'ssss', $this->config['usertable']['username'], $username, $this->config['usertable']['password'], $encryptedpassword); $statement->execute(); print_r($statement->affected_rows); //To here. if ($statement->affected_rows == 1) { $_SESSION[$this->config['sessiondata']['username']] = $username; $_SESSION[$this->config['sessiondata']['lastactivity']] = time(); $toreturn = TRUE; } else { $toreturn = FALSE; } $statement->close(); return $toreturn; } The print_r($statement->affected_rows); statement always returns -1, which means a query error. Is there a problem with the syntax of the predefined query in $statement->prepare('SELECT * FROM users WHERE ? = ? AND ? = ?') ? I really can't seem to find the problem in this code. There are no errors returned. The output from the print_r() statements are Code: [Select] Array ( [0] => Name [1] => Trey [2] => Password [3] => ...snip... )from the first print_r and Code: [Select] -1from the second. And lastly, I know that DIY login systems are generally discouraged, but this is more of a research project. I would greatly appreciate any help with this. Thanks. 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. Hello,
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>
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; } } } 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. 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. 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 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.
$start = 0; Hi all, the last 15 minutes i wasted my time pulling my hair while looking at my php code. Of course I used mysqli_error() & mysqli_errno() to find out what was happening. I got something like this: Quote warning: mysqli_error() expects exactly 1 parameter, 0 given in /wicked/fatmonkeyseatbananas/zoo/index.php on line 12 That didnt really help me. I also echoed out my query. Until I thought let's double check the field names I have in the database. They were also correct. And that's when I found out that it was in fact the property of a my ID field. It was set as primary key, but not set to auto increment. Apparently each time a new row was inserted there was a conflict since the next row also had an id of 0. After I add auto increment it was all fixed. So if anyone ever has this problem, hope this helps now it's time for a beer btw. if anyone has a faster way of solving problems like this I love to hear it. Alright when I run this query in MySQL everything goes smoothly: Code: [Select] INSERT INTO accounts (id, password, email) VALUES ('1022911', 'blahblah7', 'zzz@zzz.com') But when this runs in my script: Code: (php) [Select] $sql = "INSERT INTO accounts (id, password, email) VALUES (' {$account_number}', '{$account_password}', '{$email}')"; the id changes from the users input, I believe because the field is set to auto-increment but, I don't understand why the query works correctly through MySQL and not my script. Hi guys, i am currently working on a project that queries an inventory database through the use of radio buttons, for example; If the first button FOR THE Item(HAMMERS)is clicked, the output should be the name of the item, the number sold and the total profit(calculations) into a table. the way i have it now, when io click on the radio button my output comes back as the results for all the items in the table, i want it to display only the information about hammers, then only about each individual item when the corresponding radio button is clicked. any help would be greatly appreciated!!! I'm having trouble getting all of the results out of a query array, as it is I only get the first result and nothing else. Here's the basic code I'm working with: Code: [Select] $query = "SELECT data_txt FROM jos_servicedirectory_fields_data WHERE fieldid = 19 AND itemid = $item->itemid"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ $listtags = $row['data_txt']; $tags = "$listtags, "; $title = "<div class='servicedirectoryItemTitle'><table class=\"sdlistingitemtitle\" cellspacing=\"5\"><tbody><tr>$listingimage<td style=\"vertical-align:top;width:690px;\">$listingbasicicon<span class=\"$listingtitleclass\">$listinglogo<a href=\"{$href}\" {$onClick} title=\"{$item->title}\">{$item->title}</a></span><br /><span class=\"listingdescription\">$listingdescription</span></td><td style=\"vertical-align:top;\">$featuredribbon$moreinfobasic</td></tr></tbody></table><div class=\"listingbottom\">Tags:<span class=\"listingtags\"> $tags </span></div></div>"; } I've also tried using a foreach loop thinking that would pop all of the results but I end up not getting anything at all then. I'm guessing I'm setting the foreach loop up wrong. Here's how I'm trying to do it: Code: [Select] foreach($listtags as $value) { $tags = $value; } Does it have something to do with sticking the $tags variable in the $title variable? I wouldn't think that would matter, but the strange thing is I use this exact same query in a different part of this component and just echo it directly and it works fine. This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=313679.0 Hi All, First time posting here. I've googled the problem, but can't seem to find a response that's the same. All I want to do is have a list of id numbers and for each id number in the array, submit a MySQL query to retrieve information relating to the id number. When I execute the code below however, I end up with only the last item in the array being printed in the echo statement. Any clues? Thanks, Code: [Select] // get array of ids $ids = getIDs($ids); // loop through input list foreach ($ids as &$id) { getVarDetails($id); } function getVarDetails($local) { $con = mysql_connect('localhost:3306', 'root', '********'); if (!$con) { die('Could not connect: ' . mysql_error()); } // set database as Ensembl mysql_select_db("Ensembl", $con); $result = mysql_query("SELECT * FROM variations WHERE name = '$local' LIMIT 1"); $row = mysql_fetch_array($result) while($row = mysql_fetch_array($result)) { echo $row['name'] . " " . $row['id']; echo "<br />"; } // close connection mysql_close($con); } Ok I am trying to use mysqli instead of the usual mysql. Mysql would be outdated. With mysqli, sgl-injection is impossible if you use the "?" in those codes. I would normally use a function but I've made a simple script to find the error. I use $parameters and $sql because these are the data I need to give as parameters to the function, so I used it here too but without the function actually. Code: [Select] ini_set('display_errors',1); // 1 == aan , 0 == uit error_reporting(E_ALL | E_STRICT); # sql debug define('DEBUG_MODE',true); // true == aan, false == uit $userid = 11; $lang = 1; $newLink = "testing123"; $db_host = "localhost"; $db_gebruiker = "root"; $db_wachtwoord = ''; $db_naam = "projecteasywebsite"; $sql= "INSERT tbl_link(userid,linkcat,linksubid,linklang,linkactive,linktitle) VALUES(?, ?, ?, ?, ?, ?)"; $parameters = '"iiisis", $userid, 1, 0, $lang, 1, $newLink'; echo $parameters; $mysqli = new mysqli($db_host, $db_gebruiker, $db_wachtwoord, $db_naam); $stmt = $mysqli->prepare($sql); $stmt->bind_param($parameters); $stmt->execute(); echo "<br><br>". mysqli_connect_errno(); echo "<br><br>". mysqli_report(MYSQLI_REPORT_ERROR); $stmt->close(); $mysqli->close(); I got Wrong parameter count for mysqli_stmt::bind_param() So naturally a problem when we execute : Warning: mysqli_stmt::execute() [mysqli-stmt.execute]: (HY000/2031): No data supplied for parameters in prepared statement ($stmt->execute() Is someone using mysqli too ? When running the following code i get the error: Call to undefined method mysqli::errno() the code: $conn = new mysqli(HOST, USER, PASSWORD, DATABASE); if ($conn->errno() !== 0) { $msg = $conn->error(); throw new connErrorException($msg, 'Connect'); } I am fairly new to classes but as i understand it this should be correct. I am using mysql 5.1 so mysqli is on by default. I have even checked the php ini and everything looks fine there in respect to this. Any advice? I dont know whether the statement is correct.....i just tried it.....and it didn't work. $stmt->bind_param('ssiiiss',$_POST['name'],$_POST['email'],$_POST['d'],$_POST['m'],$_POST['y'],$_POST['add'],$_POST['phone']); here my first two values are strings and next 2 tiny int's next is int and last 2 again strings. |