I'm trying to migrate a web to mysqli and have my first question:
In mysql I had this:
$sel_user="SELECT * FROM usuarios WHERE user='$usuario_tienda'";
$rs_user=mysql_query($sel_user);
$tienda=mysql_result($rs_user,0,"tienda");
When I change to mysqli it looks like this:
$consulta_user="SELECT * FROM members WHERE username='$usuario_tienda'";
$query_user = mysqli_query($mysqli,$consulta_user);
$resultado_user = mysqli_fetch_assoc($query_user);
$tienda= $resultado_user['tienda'];
It works, but I don't think this is the best way to do it, can I do more efficient, more compressed?
you should use prepared statement, using that you can avoid sql-injection hack
$stmt = $mysqli->prepare("SELECT * FROM usuarios WHERE user=:user");
$stmt->bindParam(':user', $usuario_tienda);
$result = $stmt->execute();
$resultado_user = $result->fetch_assoc();
echo $resultado_user['tienda'];
Related
I am using MYSQL 5.5. May I know how to avoid ' in the SQL query? Below is my example query:
<?php
$mySelect1 = "'Ahli Majlis'";
$bracket_mySelect1 = "($mySelect1)";
SQL = "SELECT * FROM user where 1 and nama_gelaran in ".$bracket_mySelect1."";
?>
The wrong result I have checked in the console log data is SELECT * FROM user where 1 and nama_gelaran in ('Ahli Majlis')
Actually I want the result is SELECT * FROM user where 1 and nama_gelaran in ('Ahli Majlis')
What I tried, but it doesn't work:
SQL = SELECT * FROM user where 1 and nama_gelaran in ".html_entity_decode(htmlentities($bracket_mySelect1,ENT_QUOTES),ENT_QUOTES); .";
I am unsure how you are executing the queries but it is best practice to use PDO rather then the mysql_ functions. This also improves security and protects against mysql injection.
Below is a sample of how to connect and run a PDO query. I have changed your IN to be = as it looks like you are only passing one value.
$dsn = "mysql:host=localhost;dbname=mydb";
$user = "dbUsername";
$passwd = "dbPassword";
$name = 'Ahli Majlis';
$pdo = new PDO($dsn, $user, $passwd);
$stm = $pdo->query("SELECT * FROM `user` WHERE nama_gelaran = :name");
$stm->bindParam('name', $name);
$user = $stm->fetch();
print_r($user);
' does not come from MySQL unless that is what you INSERTed. It does come from certain PHP functions such as htmlentities. It is '.
I want to change MySQL to PDO:
$mapa = mysql_fetch_array(mysql_query("select * from mapa where id = ".$postac['mapa']." limit 1"));
$mapa_d = mysql_query("select * from mapa_d where mapa = ".$mapa['id']." ");
PHP:
$_SESSION['postac'] = $_POST['postac'];
try like this so far:
$stmt = $pdo->prepare("SELECT * FROM mapa WHERE id=:mapa");
$stmt->bindValue(':mapa', $postac, PDO::PARAM_STR);
$stmt->EXECUTE();
$postac = $stmt->fetchAll(PDO::FETCH_ASSOC);
mysql update:
mysql_query("update postac set logged = 1 where id = ".$_SESSION['postac']." limit 1");
PDO:
$stmt = $pdo->prepare("update postac set logged = 1 where id:postac");
$stmt->bindValue(':postac', $_SESSION, PDO::PARAM_STR);
$stmt->EXECUTE();
$_SESSION = $stmt->fetchAll(PDO::FETCH_ASSOC);
Does not work.
Pre-Answer Note:
I assume you have already set up a PDO connection construct ($pdo) before trying to run your PDO queries.
$mapa = mysql_fetch_array(
mysql_query("select * from mapa WHERE id = ".$postac['mapa']." limit 1"));
$mapa_d = mysql_query("select * from mapa_d WHERE mapa = ".$mapa['id']." ");
PHP:
$_SESSION['postac'] = $_POST['postac'];
try like this so far:
$stmt = $pdo->prepare("SELECT * FROM mapa WHERE id=:mapa");
$stmt->bindValue(':mapa', $postac, PDO::PARAM_STR);
$stmt->EXECUTE();
$postac = $stmt->fetchAll(PDO::FETCH_ASSOC);
PART 1:
Be Consistent
Your original statement uses a value $postac['mapa'] as an id reference in the MySQL_ query, but then your PDO statement you are passing the whole array as a value into the PDO query.
First, MySQL: id ==> $postac['mapa']
Second, PDO: id ==> $postac
So this is causing an immediate issue as you're passing a whole array in to PDO which is somehow expected to extract one value from this array. This array is being classed as a string with your PDO::PARAM_STR declaration so this is preventing the query from using this value, as it doesn't fit what it's told to expect.
Therefore this returns a NULL query.
So to fix it,
$stmt = $pdo->prepare("SELECT * FROM mapa WHERE id=:mapa");
$stmt->bindValue(':mapa', $postac['mapa'], PDO::PARAM_STR);
$stmt->execute();
$postac = $stmt->fetchAll(PDO::FETCH_ASSOC);
Part 2:
Syntax
$stmt = $pdo->prepare("update postac set logged = 1 where id:postac");
$stmt->bindValue(':postac', $_SESSION, PDO::PARAM_STR);
$stmt->EXECUTE();
$_SESSION = $stmt->fetchAll(PDO::FETCH_ASSOC);
As above, you're passing the whole $_SESSION array as a PARAM_STR value, so it's returning VOID /NULL. You also have a syntax fault that you're using WHERE id:postac, but you really mean WHERE id = :postac be careful of missing out syntax such as = !!.
PART 3:
Error Checking
It is well worth exploring and learning how to get useful error feedback on PHP PDO, as it will save you posting to StackOverfow X times a day (hopefully!)!
There is a good answer here about how to setup PDO to output errors. It is also well worth browsing the PHP Manual for PDO error checking details.
I'm sorry if this is a duplicate question but I don't know how to solve my problem. Every time I try to correct my error I fail. My code is:
if (isset($_GET["comment"])) {$id = $_GET["comment"];}
$query = "SELECT * FROM posts WHERE id = {$id['$id']};";
$get_comment = mysqli_query($con, $query);
Can anybody correct the code to not show an error anymore and tell me what did I wrong?
Try this:
$id = isset($_GET['comment']) ? $_GET['comment'] : 0;
$query = "SELECT * FROM `posts` WHERE `id` = " . intval($id);
The use of intval will protect you from SQL injection in this particular case. Ideally, you should learn PDO as it is extremely powerful and makes prepared statements much easier to handle to prevent all injections.
An example using PDO might look like:
$id = isset($_GET['comment']) ? $_GET['comment'] : 0;
$query = $pdo->prepare("SELECT * FROM `posts` WHERE `id` = :id");
$query->execute(array("id"=>$id));
$result = $query->fetch(PDO::FETCH_ASSOC); // for a single row
// $results = $query->fetchAll(PDO::FETCH_ASSOC); // for multiple rows
var_dump($result);
First of all you should prevent injestion.
if (isset($_GET["comment"])){
$id = (int)$_GET["comment"];
}
Notice, $id contanis int.
$query = "SELECT * FROM posts WHERE id = {$id}";
Assuming your $id is an integer and you only want to make the query if it is set, here's how you could do it using prepared statements, which protect you from MYSQL injection attacks:
if (isset($_GET["comment"])) {
$id = $_GET["comment"];
$stmt = mysqli_prepare($con, "SELECT * FROM posts WHERE id = ?");
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $get_comment);
while (mysqli_stmt_fetch($stmt)) {
// use $get_comment
}
mysqli_stmt_close($stmt);
}
Most of these functions return a boolean indicating whether they were successful or not, so you might want to check their return values.
This approach looks a lot more heavy duty and is arguably overkill for a simple case of a statement containing a single integer but it's a good practice to get into.
You might want to look at the object-oriented style of mysqli which you might find a little cleaner-looking, or alternatively consider using PDO.
Is there a way to execute a SQL String as a query in Zend Framework?
I have a string like that:
$sql = "SELECT * FROM testTable WHERE myColumn = 5"
now I want to execute this string directly withput parsing it and creating a Zend_Db_Table_Select object from it "by hand". Or if thats possible create a Zend_Db_Table_Select object from this string, to execute that object.
How can I do that? I didn't find a solution for this in the Zend doc.
If you're creating a Zend_DB object at the start you can create a query using that. Have a look at this entry in the manual : https://framework.zend.com/manual/1.12/en/zend.db.statement.html
$stmt = $db->query(
'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?',
array('goofy', 'FIXED')
);
Or
$sql = 'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?';
$stmt = new Zend_Db_Statement_Mysqli($db, $sql);
If you are using tableGateway, you can run your raw SQL query using this statement,
$this->tableGateway->getAdapter()->driver->getConnection()->execute($sql);
where $sql pertains to your raw query. This can be useful for queries that do not have native ZF2 counterpart like TRUNCATE / INSERT SELECT statements.
You can use the same query in Zend format as
$select = db->select()->from(array('t' => 'testTable'))
->$where= $this->getAdapter()->quoteInto('myColumn = ?', $s);
$stmt = $select->query();
$result = $stmt->fetchAll();
Here is an example for ZF1:
$db =Zend_Db_Table_Abstract::getDefaultAdapter();
$sql = "select * from user"
$stmt = $db->query($sql);
$users = $stmt->fetchAll();
I know that I need prepared statements because I make more than one call to my database during one script.
I would like to get concrete examples about the following sentence
Look at typecasting, validating and sanitizing variables and using PDO with prepared statements.
I know what he mean by validating and sanitizing variables. However, I am not completely sure about prepared statements. How do we prepare statements? By filters, that is by sanitizing? Or by some PDO layer? What is the definition of the layer?
What do prepared statements mean in the statement? Please, use concrete examples.
What do prepared statements mean in
the statement?
From the documentation:
This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed.
See pg_prepare
Example from the page linked above:
<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");
// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));
// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
?>
The MySQL documentation for Prepared Statements nicely answers the following questions:
Why use prepared statements?
When should you use prepared
statements?
It means it will help you prevent SQL injection attacks by eliminating the need to manually quote the parameters.
Instead of placing a variable into the sql you use a named or question mark marker for which real values will be substituted when the statement is executed.
Definition of PDO from the PHP manual:
'The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP.'
See the php manual on PDO and PDO::prepare.
An example of a prepared statement with named markers:
<?php
$pdo = new PDO('pgsql:dbname=example;user=me;password=pass;host=localhost;port=5432');
$sql = "SELECT username, password
FROM users
WHERE username = :username
AND password = :pass";
$sth = $pdo->prepare($sql);
$sth->execute(array(':username' => $_POST['username'], ':pass' => $_POST['password']));
$result = $sth->fetchAll();
An example of a prepared statement with question mark markers:
<?php
$pdo = new PDO('pgsql:dbname=example;user=me;password=pass;host=localhost;port=5432');
$sql = "SELECT username, password
FROM users
WHERE username = ?
AND password = ?";
$sth = $pdo->prepare($sql);
$sth->execute(array($_POST['username'], $_POST['password']));
$result = $sth->fetchAll();
How do we prepare statements:
You define a query one time, and can called it as often as you like with different values. (eg. in a loop)
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));
$result = pg_execute($dbconn, "my_query", array("row two"));
$result = pg_execute($dbconn, "my_query", array("row three"));
see: http://us2.php.net/manual/en/function.pg-execute.php
Reply to Karim79's answer
This
$result = pg_prepare($dbconn, "query1", 'SELECT passhash_md5 FROM users WHERE email = $1');
seems to be the same as this
$result = pg_prepare($dbconn, "query1", 'SELECT passhash_md5 FROM users WHERE email = ?');
Conclusion: the use of pg_prepare and pg_execute makes PHP much more efficient, since you do not need to consider sanitizing. It also helps you in the use of PDO.