Is it possible to use * in query for $stmt->prepare() and using bind_result()?
For example I have to select 50 columns in 1 table with conditions as parameter, and if I type all 50 columns it will take time.
So in this scenario how can I get the result?
$stmt->prepare("Select * from table where col1 = ? and col2=? and col3=? and col4=?")
$stmt->bind_param("ssss",$col1, $col2, $col3, $col4)
$stmt->execute()
Yes, of course.
Just use $res = $stmt->get_result() followed by familiar $row = $res->fetch_assoc() stuff
However, for a newbie, you are indeed strictly advised to choose PDO over mysqli.
Only the question mark is used as a placeholder character by mysqli, so you can use * just as you usually would.
To save time, if you are using PDO, you can name your parameters and then mass assign them.
E.g.
$sql = 'SELECT *
FROM table
WHERE col1=:myval OR col2=:myval OR col3=:myval';
$sth = $dbh->prepare($sql);
$sth->execute(array(':myval ' => 150));
$red = $sth->fetchAll();
Related
Before moving to PDO, I used
$result = mysqli_query ($conn, 'SELECT * FROM mytable WHERE id = 54');
if (mysqli_num_rows($result) >= 1) { ... }
to check if the query returns at least one result.
Now with PDO, I've seen in many SO questions (like get number of rows with pdo) that there is no direct function in PDO to check the number of rows of a query (there are warnings about the use of$result->rowCount();), but rather solutions like doing an extra query:
SELECT count(*) FROM mytable WHERE id = 54
But this is maybe too much for what I want : in fact, I don't need the exact number of rows, but just if there is at least one.
How to check if a prepared statement query returns at least one row ?
$stmt = $db->prepare('SELECT * FROM mytable WHERE id = 54');
$stmt.execute();
... // HOW TO CHECK HERE?
$stmt = $db->prepare('SELECT * FROM mytable WHERE id = 54');
$stmt.execute();
... // HOW TO CHECK HERE?
It's so simple, you're almost there already.
$stmt = $db->prepare('SELECT * FROM mytable WHERE id = 54');
$stmt.execute();
$result = $stmt->fetchAll(); // Even fetch() will do
if(count($result)>0)
{
// at least 1 row
}
And if you just want Yes/No answer then you should also add a LIMIT 1 to your query so mysql doesn't waste trying to look for more rows.
I'm trying to execute this:
$colparam = 'abcd';
$stmt = $db->prepare("SELECT DISTINCT ? AS kol FROM katalog ORDER BY kol ASC");
$stmt->execute(array($colparam));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
and it's not working (no errors, just empty array as result).
Instead this works fine:
$stmt = $db->prepare("SELECT DISTINCT abcd AS kol FROM katalog ORDER BY kol ASC");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
So is there any catch with the use of parameter as a name of the column in PDO?
No, you can't use parameter replacements for any database objects (tables, columns, etc.) in MySQL.
When you think about what a prepared statement actually is, this makes complete sense. As how can MySQL prepare a query execution plan when it does not even know the database objects involved.
I certainly wish that more documentation would actually cover what a prepared statement actually does (beyond it's obvious use for parametrization).
Here is link to MySQL prepared statement documentation for more reading:
https://dev.mysql.com/doc/refman/5.6/en/sql-syntax-prepared-statements.html
While introducing myself to pgSQL prepared statements, I've successfully returned the results of a few queries. However, I have a few questions.
Given the following query:
$w_ft = "36";
$sth = $dbh->prepare("SELECT * FROM main_products_common_dimensions WHERE w_ft = :w_ft");
$sth->bindParam(':w_ft', $theId, PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetchAll();
I notice that even though the column in the main_products_common_dimensions table is a character_varying, I get the same/correct result set returned if I use
$w_ft = 36;
...
$sth->bindParam(':w_ft', $w_ft, PDO::PARAM_INT);
and
$w_ft = "36";
...
$sth->bindParam(':w_ft', $w_ft, PDO::PARAM_STR);
and
$w_ft = "36";
...
$sth->bindParam(':w_ft', $w_ft, PDO::PARAM_INT);
and
$w_ft = 36;
...
$sth->bindParam(':w_ft', $w_ft, PDO::PARAM_STR);
That is, no matter how I bind the parameter _INT or _STR or set the variable (integer or string), the data is returned correctly. Is this normal behavior?
From http://php.net/manual/en/pdostatement.bindparam.php, I see that the parameter datatype is explained
Explicit data type for the parameter using the PDO::PARAM_* constants.
To return an INOUT parameter from a stored procedure, use the bitwise
OR operator to set the PDO::PARAM_INPUT_OUTPUT bits for the data_type
parameter.
What is meant by "returning an INOUT parameter from a stored procedure"? Is this related? Does that imply that I am not using a stored procedure? Length seems to be optional, though that is not indicated in its explanation. Are there advantages to providing it?
As you can see, I'm quite new to this, and just trying to get my head around it. Thank you very much
PDO::PARAM_INT and PDO::PARAM_STR when passed to bindParam() are indications that the driver is free to ignore.
Looking at PDO pg driver's source code, it appears that, except for PDO_PARAM_LOB which is treated specially, all types are quoted as strings (that is, between quotes and passed to libpq's PQescapeStringConn function)
You should also be aware of the PDO::ATTR_EMULATE_PREPARES attribute that controls what method is used under the hood. When false, PQprepare() is used with real out-of-query parameters. If true, parameter values are injected into the SQL passed to the non-parametrized PQexec().
Technically, this is quite different, so you may see differing behaviors in corner cases or error cases depending on this attribute.
$w_ft = 36;
...
$sth->bindParam(':w_ft', $theId, PDO::PARAM_INT);
should be
$w_ft = 36;
...
$sth->bindParam(':w_ft', $w_ft, PDO::PARAM_INT);
This is because postgres accepts the quoting of integers when comparing with an integer column.
So if your id column is an int, these queries both work the same:
SELECT * FROM mytable WHERE id = 1;
SELECT * FROM mytable WHERE id = '1';
What the PDO::PARAM_* constants do is modify the way the quoting/escaping is done to the values, and is independent of the value datatype. Php also will make a type conversion if needed. If you choose PDO::PARAM_INT you are telling the DBMS driver that the value of $id is an integer, and should escape it as an integer, so it will not add quotes around it when it puts the value into the query.
$id = 1;
$sth = $db->prepare("SELECT * FROM mytable WHERE id = :id");
$sth->bindParam(':id', $id, PDO::PARAM_INT);
// resulting query would be SELECT * FROM mytable WHERE id = 1;
$sometext = "hello";
$sth = $db->prepare("SELECT * FROM mytable WHERE id = :id");
$sth->bindParam(':id', $sometext, PDO::PARAM_INT);
// in this case, $sometext will be casted to an integer, that will result in (int)0
// resulting query would be SELECT * FROM mytable WHERE id = 0;
$sometext = "hello";
$sth = $db->prepare("SELECT * FROM mytable WHERE id = :id");
$sth->bindParam(':id', $sometext, PDO::PARAM_STR);
// in this case, $sometext is already a string, and strings should be quoted
// resulting query would be SELECT * FROM mytable WHERE id = 'hello';
Also, about the INOUT param of bindParam, if you aren't going to use INOUT or OUT parameters of a stored procedure (like, say, passing a reference to a function call than is setted inside the function), you probably are better using bindValue. Using bindValue you can put the result of a function or any constant value as the value to bind, you don't need to put a variable.
$sth->bindValue(':something', 5);
$sth->bindValue(':something_else', $foo->bar());
I have a PHP search suggestion script which uses MySQL as its back-end. I am aware there are many vunerabilities in my code, I was just wondering what I can do to make it more secure.
Here is my code:
<?php
$database=new mysqli('localhost','username','password','database');
if(isset($_POST['query'])){
$query=$database->real_escape_string($_POST['query']);
if(strlen($query)>0){
$suggestions=$database->query(
"SELECT * FROM search WHERE name LIKE '%" . $query .
"%' ORDER BY value DESC LIMIT 5");
if($suggestions){
while($result=$suggestions->fetch_object()){
echo '<a>'.$result->name.'</a>';
}
}
}
}
?>
Actually there aren't, considering you are escaping the only external value in the SQL
Anyway I suggest you to use PDO::prepare for queries. Go here for further infos
http://it.php.net/manual/en/pdo.prepare.php
Example:
$sth = $dbh->prepare('SELECT * FROM article WHERE id = ?');
$sth->execute(array(1));
$red = $sth->fetchAll();
Some tips from me:
use PDO,
don't concatenate query parameters, use prepared statements in PDO,
don't put "*" in SELECT statement, get only the columns you'll need,
use fetchAll() in PDO, don't fetch records in while() loop.
I want to create prepared stmt such as
"SELECT id,latitude,longitude
FROM sometable WHERE
(3437.74677 * ACOS(SIN(latitude_radians) * SIN(?) +
COS(latitude_radians)*COS(?) * COS(longitude_radians - ?))) <= ?";
in PHP. Where clause is a function of column values and bind variables
but how should I bind the values. Or is this even a legal prepared stmt?
Thanks in advance,
-v-
I don't see any problem here.
See:
PHP Prepared Statements.
Extremely minimal sample:
$stmt = $dbh->prepare( $QUERY );
$stmt->execute( $arguments_array )
Sorry for being unclear.
As I understand following is an example of PHP prepared stmt,
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name'])))
Now the where clause is always a simple, column = ? AND column2 = ?. In my case though its function and it didnt work when assigned values to the bind variables. I will regenerate the error again and post it.
I was wondering then if it is even legal to have a function of column names and bind variables in the where clause.