I have written a method to get a value out of a database based on an id.
I would like to use the variable id as a parameter in mysql but I can't get it to work.
Here is my code:
function get_color_by_id($id) {
$mysqli = new mysqli("localhost", "root", "usbw", "ipadshop", 3307);
if($mysqli->connect_errno){
die("Connection error: " . $mysqli->connect_error);
}
set #id := $id;
$result = $mysqli->query('SELECT kleur FROM kleur WHERE id=',#id);
if(!$result){
die('Query error: ' . $mysqli->error);
}
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
return $row;
}
}
PHP is not SQL; and SQL code should not be expected to work in a PHP context. The procedural SQLish syntax (set #id := $id) is thus invalid in context, as is the #id expression used later.
As shown here (and updated for this question), the correct way to use parameters in mysqli is with prepare, bind_param, and execute.
$stmt = $mysqli->prepare('SELECT kleur FROM kleur WHERE id = ?');
$stmt->bind_param('i', $id); // assuming $id represents an integer
$result = $stmt->execute();
Since bind_param uses reference calling semantics, the variables used should not be re-assigned once bound to avoid potential confusion.
Also, it can be confusing to give the same names to columns and tables; my preference is to use plural names for tables/relations, and to refine the column names more. Consider a query with different names chosen;
SELECT kleurNaam FROM kleuren WHERE id = ?
-- or in English
SELECT colorName FROM colors WHERE id = ?
Easier to read, no?
Related
This question already has answers here:
PDO bindParam issue [duplicate]
(2 answers)
Closed 8 years ago.
I'm trying to perform a SELECT from my database, but I'm getting an error and I don't understand why. All I can tell is that it seems to be failing at the prepare() statement. Any help would be appreciated.
$sQuery = "SELECT * FROM ? WHERE `email` = ? AND `password` = ?";
$sTypes = "sss";
$aParams = array("user", "john.doe#missing.com", "password");
Above is the query and bind_param values.
function conn($sQuery, $sTypes=null, $aParams=null){
$sMessage = '';
$db = new mysqli('localhost','root','','myvyn') or die('unable to connect!');
if($db->connect_errno){
$message = $db->connect_error;
} else{
$stmt = $db->stmt_init();
if (!($stmt->prepare($sQuery))) {
var_dump("Prepare failed: (" . $stmt->errno . ") " . $stmt->error);
}
if($sTypes&&$aParams){
$bindParams[] = $sTypes;
foreach($aParams as $param){
$bindParams[] = $param;
}
call_user_func_array(array($stmt, 'bind_param'), $bindParams);
}
$stmt->execute();
$oResult = $stmt->get_result();
while($rows = $oResult->fetch_assoc()){
$aRows[] = $rows;
}
$oResult->free();
$db->close();
return $aRows;
}
}
You cannot use parameters for a table name, as per here (my bold):
The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement, or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. It's not allowed to compare marker with NULL by ? IS NULL too. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements.
Assuming you control the table name (so SQL injection is impossible), you could use something like:
$sQuery = "SELECT * FROM $tblname WHERE `email` = ? AND `password` = ?";
and then only bind the email address and password.
I am using nested queries to retrieve information from multiple tables. I need advice on optimizing this php code.
This function creates an object.
public function conn($query){
$mysqli = new mysqli('test','test','test','test');
$result = $mysqli->query("SET NAMES utf8");
$result = $mysqli->query("set character_set_client='utf8'");
$result = $mysqli->query("set collation_connection='utf8_general_ci'");
$result = $mysqli->query($query);
$mysqli->close();
return $result;
}
This code uses that function.
$connect = $this->conn("SELECT * FROM Table LIMIT 100000");
while($i = $connect->fetch_assoc()){
$name = $i["name"];
$connect2 = $this->conn("SELECT * FROM Names WHERE Name = '$name'");
if($connect2 ->num_rows > 0){
echo $name.'<br>';
}
}
Need recommendations for a connection to the database.
In the while loop, as you see, I am checking for the presence of $name in other table. But I am opening and closing a connection every time through the loop. And this will be 100001 connection opens and closes.
Is it possible to open a connection to the database only once?
P.S.: The SQL is an example - Please don't suggest changes there, because I am trying to figure out how to handle the repeated queries, not optimize the SQL.
Connection objects are reusable. Make a connection, then use it to make as many queries as you want. Close each query (that is, each result set) when you're done with it, then close the connection at the end of the run.
Closing a connection is a network operation, so it takes a while. Closing a query is mostly an in-memory operation, so it is faster.
In your example, you're using nested queries (more on that in a moment). Your code should end up looking something like this pseudocode:
public function getconn(){
$mysqli = new mysqli('test','test','test','test');
$mysqli->query("SET NAMES utf8");
$mysqli->query("set character_set_client='utf8'");
$mysqli->query("set collation_connection='utf8_general_ci'");
return $mysqli; /* return the connection handle */
}
$conn1 = getconn();
$conn2 = getconn();
$resultset1 = $conn1->query("SELECT * FROM Table LIMIT 100000");
while($i = $resultset1->fetch_assoc()){
$name = $i["name"];
$resultset2 = $conn2->query("SELECT * FROM Names WHERE Name = '$name'");
if($resultset2->num_rows > 0){
echo $name.'<br>';
}
$resultset2->close();
}
$resultset1->close();
$conn1->close();
$conn2->close();
(Please note; I haven't debugged this code.)
To take this optimization one step further, you should consider using a prepared statement for the query inside the while loop. Here's documentation on that http://php.net/manual/en/mysqli-stmt.fetch.php.
$conn1 = getconn();
$conn2 = getconn();
/* create a prepared statement with placeholder parameter ? */
$stmt = $mysqli->prepare("SELECT * FROM Name WHERE Name = ?"));
$name = '';
$name_out = '';
$stmt->bind_param("s", $name);
$stmt->bind_result($name_out);
$resultset1 = $conn1->query("SELECT * FROM Table LIMIT 100000");
while($i = $resultset1->fetch_assoc()){
$name = $i["name"];
$resultset2 = $stmt->execute(); /* run query with bound parameter */
if ($stmt_fetch() ( {
echo $name.'<br>';
}
$resultset2->close();
}
$resultset1->close();
$conn1->close();
$conn2->close();
(Please note; I haven't debugged this code either.)
Now, it's possible your pair of queries are just an example to show a set of nested queries. If so, that's fine. But, you are performing this task (retrieve 100K names) in an almost unimaginably inefficient way. You've said you don't want anybody to rewrite this query, but I am sorry, I can't just let this one pass.
This code would do a far more streamlined job.
$conn = getconn();
$q = "SELECT t.name FROM Table t JOIN Name n ON t.name = n.name LIMIT 100000";
$resultset = $conn->query($q);
while($i = $resultset->fetch_assoc()){
$name = $i["name"];
echo $name.'<br>';
}
$resultset->close();
$conn->close();
It's more efficient for two reasons. First, it doesn't use SELECT *, which ends up sending all sorts of data over the network from your MySQL server to your php program, just to throw it away.
Second, it doesn't use the nested queries. Instead, the JOIN query pulls all the name columns from Table that have a matching name column in Names.
I'm using the following snippet:
mysql_connect($host,$user,$password);
$sql = "SELECT FROM ec_opps WHERE id=" . $_GET["UPDATE"];
$item = mysql_query($sql);
mysql_close();
print_r($item);
To try and retrieve data based on the UPDATE value. This value prints to the page accurately, and I know the IDs I'm requesting exist in the database. The print_r($item) function returns no result, not even an empty array, so I'm confused as to where I'm going wrong.
I know it isn't best practise to use MySQL like this, but I'm doing it for a reason.
You're missing columns to be selected in your SELECT query, or you can select all by putting *, which means selecting all column.
$sql = "SELECT * FROM ec_opps WHERE id='" . $_GET["UPDATE"]."'";
Your query is very prone to SQL injections.
You should refrain from using MySQL. It's deprecated already. You should be at least using MySQLi_* instead.
<?php
/* ESTABLISH CONNECTION */
$mysqli = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT column1, column2 FROM ec_opps WHERE id=?"; /* REPLACE NEEDED COLUMN OR ADD/REMOVE COLUMNS TO BE SELECTED */
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("s", $_GET["UPDATE"]); /* BIND GET VALUE TO THE QUERY */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($column1,$column2); /* BIND RESULTS */
while ($stmt->fetch()) { /* FETCH RESULTS */
printf ("%s (%s)\n", $column1, $column2);
}
$stmt->close();
}
$mysqli->close();
?>
Replace with this code
$sql = "SELECT * FROM ec_opps WHERE id=" . $_GET["UPDATE"];
You are missing * in your query.
You need to use:
SELECT * FROM
instead of
SELECT FROM
There is a syntax error in the query. It is missing *. Try with -
$sql = "SELECT * FROM ec_opps WHERE id='" . $_GET["UPDATE"] . "'";
Please avoid using mysql. Try to use mysqli or PDO. mysql is deprecated now.
Could somebody please point me in the right direction. I am in the process of making the transition from MySql to MySqli. Normally I would select from the database using th code below and it would allow me to easily use the column value as a working variable:
$SQLCommand = "SELECT * FROM table WHERE column1 = 'ok'";
$Data = mysql_query($SQLCommand);
$DataRow = mysql_fetch_assoc($Data);
$var1 = $DataRow["column1"];
$var2 = $DataRow["column2"];
$var3 = $DataRow["column3"];
$var4 = $DataRow["column4"];
I have researched how to do the MySql equivalent but I find theres a lot of different way using loops etc. Is there a like for like (for want of a better description) that does the same thing? Thanks in advance.
Instead of going with the flow, i care to suggest a PDO alternative
$db = new PDO($dsn, 'username','password');
//$dsn is the connection string to your database.
//See documentation for examples
//The next two rows are optional, but i personally suggest them to
//ease developing, debugging (the 1st) and fetching results (the 2nd)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$stmt = $db->prepare("SELECT * FROM table WHERE column1 = :c1");
$stmt->bindValue(':c1', 'ok'); //This example is trivial and not necessary
//but it gains relevance when the bound value
//is a variable
$rows = $stmt->fetchAll(); //if you expect a single row use fetch() instead
//do something with the results
You can read more about PDO here: PDO manual
The biggest PDO advantage is that it's independent of the actual database in use by your application. If, by chance, you want to change database in the future, for example SQLITE or PostgreSQL, the only* change you have to make is your $dsn connection string
[*] True only if you used standard SQL queries and nothing vendor-specific.
A direct conversion would be:
$Data = mysqli_query($connection, $SQLCommand);
$DataRow = mysqli_fetch_assoc($Data);
The difference, other than the i is that mysqli_query requires the connection as an argument (as do most mysqli_* functions).
MySQLi also has an object oriented style:
$Data = $connection->query($SQLCommand); // assuming you created the $connection object
$DataRow = $data->fetch_assoc();
They should be like
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
$SQLCommand = "SELECT * FROM table WHERE column1 = 'ok'";
$Data = $mysqli->query($SQLCommand);
$DataRow = $mysqli->fetch_assoc($Data);
Try this LINK
My suggestion is to use mysqli prepared statement whenever you are using user inputs to prevent SQL injection:
See below code uses object oriented approach and prepared statement
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
!$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
!$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = ?");
/* Prepared statement, stage 2: bind and execute */
$id = 1;
//note below "i" is for integer, "s" can be used for string
if (!$stmt->bind_param("i", $id)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>
I am new to using prepared statements in mysql with php. I need some help creating a prepared statement to retrieve columns.
I need to get information from different columns. Currently for a test file, I use the completely unsecure SQL statement:
$qry = "SELECT * FROM mytable where userid='{$_GET['userid']}' AND category='{$_GET['category']}'ORDER BY id DESC"
$result = mysql_query($qry) or die(mysql_error());
Can someone help me create a secure mysql statement using input from url parameters (as above) that is prepared?
BONUS: Prepared statements are suppose to increase speed as well. Will it increase overall speed if I only use a prepared statement three or four times on a page?
Here's an example using mysqli (object-syntax - fairly easy to translate to function syntax if you desire):
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("SELECT * FROM mytable where userid=? AND category=? ORDER BY id DESC");
$stmt->bind_param('ii', intval($_GET['userid']), intval($_GET['category']));
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column1, $column2, $column3);
while($stmt->fetch())
{
echo "col1=$column1, col2=$column2, col3=$column3 \n";
}
$stmt->close();
Also, if you want an easy way to grab associative arrays (for use with SELECT *) instead of having to specify exactly what variables to bind to, here's a handy function:
function stmt_bind_assoc (&$stmt, &$out) {
$data = mysqli_stmt_result_metadata($stmt);
$fields = array();
$out = array();
$fields[0] = $stmt;
$count = 1;
while($field = mysqli_fetch_field($data)) {
$fields[$count] = &$out[$field->name];
$count++;
}
call_user_func_array(mysqli_stmt_bind_result, $fields);
}
To use it, just invoke it instead of calling bind_result:
$stmt->store_result();
$resultrow = array();
stmt_bind_assoc($stmt, $resultrow);
while($stmt->fetch())
{
print_r($resultrow);
}
You can write this instead:
$qry = "SELECT * FROM mytable where userid='";
$qry.= mysql_real_escape_string($_GET['userid'])."' AND category='";
$qry.= mysql_real_escape_string($_GET['category'])."' ORDER BY id DESC";
But to use prepared statements you better use a generic library, like PDO
<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT * FROM mytable where userid=? and category=?
order by id DESC');
$sth->execute(array($_GET['userid'],$_GET['category']));
//Consider a while and $sth->fetch() to fetch rows one by one
$allRows = $sth->fetchAll();
?>
Or, using mysqli
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$category = $_GET['category'];
$userid = $_GET['userid'];
/* create a prepared statement */
if ($stmt = mysqli_prepare($link, 'SELECT col1, col2 FROM mytable where
userid=? and category=? order by id DESC')) {
/* bind parameters for markers */
/* Assumes userid is integer and category is string */
mysqli_stmt_bind_param($stmt, "is", $userid, $category);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $col1, $col2);
/* fetch value */
mysqli_stmt_fetch($stmt);
/* Alternative, use a while:
while (mysqli_stmt_fetch($stmt)) {
// use $col1 and $col2
}
*/
/* use $col1 and $col2 */
echo "COL1: $col1 COL2: $col2\n";
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>
I agree with several other answers:
PHP's ext/mysql has no support for parameterized SQL statements.
Query parameters are considered more reliable in protecting against SQL injection issues.
mysql_real_escape_string() can also be effective if you use it correctly, but it's more verbose to code.
In some versions, international character sets have cases of characters that are not escaped properly, leaving subtle vulnerabilities. Using query parameters avoids these cases.
You should also note that you still have to be cautious about SQL injection even if you use query parameters, because parameters only take the place of literal values in SQL queries. If you build SQL queries dynamically and use PHP variables for the table name, column name, or any other part of SQL syntax, neither query parameters nor mysql_real_escape_string() help in this case. For example:
$query = "SELECT * FROM $the_table ORDER BY $some_column";
Regarding performance:
The performance benefit comes when you execute a prepared query multiple times with different parameter values. You avoid the overhead of parsing and preparing the query. But how often do you need to execute the same SQL query many times in the same PHP request?
Even when you can take advantage of this performance benefit, it is usually only a slight improvement compared to many other things you could do to address performance, like using opcode caching or data caching effectively.
There are even some cases where a prepared query harms performance. For example in the following case, the optimizer can't assume it can use an index for the search, because it must assume the parameter value might begin with a wildcard:
SELECT * FROM mytable WHERE textfield LIKE ?
Security with MySQL in PHP (or any other language for that matter) is a largely discussed issue. Here are a few places for you to pick up some great tips:
http://webmaster-forums.code-head.com/showthread.php?t=939
http://www.sitepoint.com/article/php-security-blunders/
http://dev.mysql.com/tech-resources/articles/guide-to-php-security.html
http://www.scribd.com/doc/17638718/Module-11-PHP-MySQL-Database-Security-16
The two most major items in my opinion are:
SQL Injection: Be sure to escape all of your query variables with PHP's mysql_real_escape_string() function (or something similar).
Input Validation: Never trust the user's input. See this for a tutorial on how to properly sanitize and validation your inputs.
If you're going to use mysqli - which seems the best solution to me - I highly recommend downloading a copy of the codesense_mysqli class.
It's a neat little class that wraps up and hides most of the cruft that accumulates when using raw mysqli such that using prepared statements only takes a line or two extra over the old mysql/php interface
Quite late, but this might help someone:
/**
* Execute query method. Executes a user defined query
*
* #param string $query the query statement
* #param array(Indexed) $col_vars the column variables to replace parameters. The count value should equal the number of supplied parameters
*
* Note: Use parameters in the query then supply the respective replacement variables in the second method parameter. e.g. 'SELECT COUNT(*) as count FROM foo WHERE bar = ?'
*
* #return array
*/
function read_sql($query, $col_vars=null) {
$conn = new mysqli('hostname', 'username', 'user_pass', 'dbname');
$types = $variables = array();
if (isset($col_vars)) {
for ($x=0; $x<count($col_vars); $x++) {
switch (gettype($col_vars[$x])) {
case 'integer':
array_push($types, 'i');
break;
case 'double':
array_push($types, 'd');
break;
default:
array_push($types, 's');
}
array_push($variables, $col_vars[$x]);
}
$types = implode('', $types);
$sql = $conn->prepare($query);
$sql -> bind_param($types, ...$variables);
$sql -> execute();
$results = $sql -> get_result();
$sql -> close();
}else {
$results = $conn->query($query) or die('Error: '.$conn->error);
}
if ($results -> num_rows > 0) {
while ($row = $results->fetch_assoc()) {
$result[] = $row;
}
return $result;
}else {
return null;
}
}
You can then invoke the function like so:
read_sql('SELECT * FROM mytable where userid = ? AND category = ? ORDER BY id DESC', array($_GET['userid'], $_GET['category']));