How to write MySQL query that uses a PHP variable? - php

How to place a php variable into query?
$shopid = $pdo->query('SELECT shopid FROM `shop` WHERE shopname='$shopname'')->fetchAll(PDO::FETCH_ASSOC);
This is not working, the error message show:
"Parse error: syntax error, unexpected '$shopname' (T_VARIABLE)"

No
Do not insert parameters this way. You should be using bindParam
$statement = $db->prepare('SELECT shopid FROM shop WHERE shopname=:shopname');
$statement->bindParam(':shopname', $shopname, PDO::PARAM_STR);
$statement->execute();

If $shopname is coming from an untrusted source, you are wide open to SQL injection. To fix this, you should make use of PDO and it's prepared statement API:
$query = $pdo->prepare("SELECT shopid FROM shop WHERE shopname = ?");
$query->bindValue(1, $shopname, PDO::PARAM_STR);
$query->execute();
$shopid = $query->fetchAll(PDO::FETCH_ASSOC);

if you support the PDO ,why not use the prepare, and it is more safe.
$stmt = $pdo->prepare('SELECT shopid FROM shop WHERE shopname=:shopname');
$stmt->bindParam(':shopname', $shopname);
$shopname = $yourdefined;
$stmt->execute();
$stmt->bindColumn(1, $shopid);
while($stmt->fetch()){
echo $shopid,PHP_EOL;
}
Well,you can also use the base sql like this:
$shopid = $pdo->query('SELECT shopid FROM `shop` WHERE shopname=\'{$shopname}\'')->fetchAll(PDO::FETCH_ASSOC);

You weren't wrapping your query properly.
$shopid = $pdo->query("SELECT shopid FROM `shop` WHERE `shopname`='$shopname'");

Try This:
$query = "SELECT shopid FROM shop WHERE shopname= '".$shopname."'";
$result = mysql_query($query);

Related

Prepared statements when working with set operations

I've got a simple query that is not so easy to execute in PHP script:
SELECT `title` from `MY_TABLE` WHERE id in (30,32,33,44)
Usually I execute sql queries with prepared statements. I place a bunch of ? and than bind parameters. This time the numbers in parenthesis are an array of data I get from the user.
I tried this, but it does not work:
$ids = [30,32,33,44];
$stmt = $mysqli->prepare("
SELECT `title` from `MY_TABLE` WHERE id in (?)
");
// $stmt->bind_param();
$stmt->bind_param("i",$ids);
$stmt->execute();
$stmt->bind_result($title);
$stmt->store_result();
//fetch
How can I execute a set operation with prepared statements?
UPDATE:
After following your advice I came up with this
$ids = [30,32,33,44];
$questionMarks = rtrim(str_repeat('?,',count($ids)),", ");
$parameters = str_repeat('i',count($ids));
echo $questionMarks."<br>";
echo $parameters."<br>";
$stmt = $mysqli->prepare("
SELECT `title` from `MY_TABLE` WHERE id in (".$questionMarks.")
");
$scene_names = [];
$stmt->bind_param($parameters, $ids); //error here
$stmt->execute();
$stmt->bind_result($title);
$stmt->store_result();
I am still getting an error. This time it says:
Number of elements in type definition string doesn't match number of bind variables
I am not sure why it thinks that the number of elements (what is element in this case?) is wrong.
UPDATE 2:
Instead of:
$stmt->bind_param($parameters, $ids); //error here
I used:
$stmt->bind_param($parameters, ...$ids); //error gone
Taraam. Works fine.
Something like:
$ids = [30,32,33,44];
$types = array();
foreach($ids as $i){
array_push($types,'i');
}
$params = array_merge($ids,$types);
$sqlIN = str_repeat('?,',count($ids));
$sqlIN = rtrim($sqlIN, ',');
//Value of $sqlIN now looks like ?,?,?,?
$sql = "SELECT title from MY_TABLE WHERE id IN ($sqlIN)";
$stmt = $mysqli->prepare($sql);
call_user_func_array(array($stmt, 'bind_param'), $params);
$stmt->execute();
$stmt->bind_result($id);
$stmt->store_result();

PHP/MySQL to PDO

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.

Anything wrong with this MySQL query?

$stmt = $connection->prepare("SELECT id FROM articles WHERE position =? LIMIT 1");
$stmt-> bind_param('i',$call );
$stmt->execute();
$result = $stmt->fetch();
$oldpostid = $result;
$stmt->close();
I don't see anything wrong with it, but it is returning 1 or nothing. $call is set and integer. I tried this too:
$stmt = $connection->prepare("SELECT * FROM articles WHERE position =? LIMIT 1");
$oldpostid = $result['id'];
Assuming this is all working you need to bind the result variables as well. mysqli_stmt_fetch returns a boolean:
$stmt->execute();
$stmt->bind_result($id);
$stmt->fetch();
$oldpostid = $id;
You seem to be mixing mysqli & PDO. The first line is PDO
$stmt = $connection->prepare("SELECT id FROM articles WHERE position =? LIMIT 1");
The next line is mysqli
$stmt-> bind_param('i',$call );
Should be for PDO the unnamed variables in place holder Manual Example 4
$stmt-> bindParam(1,$call );
$stmt->execute();
OR using array
$stmt->execute(array($call));

php bind_result

I have this sequence of code:
$connection = new mysqli('localhost','root','','db-name');
$query = "SELECT * from users where Id = ?";
$stmt = $connection->prepare($query);
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->bind_result($this->id,$this->cols);
$stmt->fetch();
$stmt->close();
$connection->close();
The problem is that the "SELECT" might give a variable number of columns, which i retain in $this->cols. Is there any possibility to use bind_result with a variable number of parameters?...or any alternative to the solution.
if you are lucky enough to run PHP 5.3+, mysqli_get_result seems what you want.
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_array();

How can I properly use a PDO object for a parameterized SELECT query

I've tried following the PHP.net instructions for doing SELECT queries but I am not sure the best way to go about doing this.
I would like to use a parameterized SELECT query, if possible, to return the ID in a table where the name field matches the parameter. This should return one ID because it will be unique.
I would then like to use that ID for an INSERT into another table, so I will need to determine if it was successful or not.
I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.
$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();
You can use the bindParam or bindValue methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
A litle bit complete answer is here with all ready for use:
$sql = "SELECT `username` FROM `users` WHERE `id` = :id";
$q = $dbh->prepare($sql);
$q->execute(array(':id' => "4"));
$done= $q->fetch();
echo $done[0];
Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();
I hope this help someone, Enjoy!
Method 1:USE PDO query method
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Getting Row Count
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Method 2: Statements With Parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Method 3:Bind parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Want to know more look at this link
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}

Categories