I've written this simple code to retrieve a value of a table which starts with a variable coming from a POST method: i know that in my table there is only that value, so i want to retrieve the unique value in a string variable:
...
$query = "SELECT * FROM news WHERE contenuto LIKE :contenuto%";
$query_params = array(
':contenuto' => $_POST['contenuto']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}catch (PDOException $ex){
}
$row = $stmt->fetch();
$this = $row['contenuto'];
echo $this;
...
But this code doesn't work because nothing in showed by echo.. any help?
The % wildcard should be in the bound variable and not the prepared statement
$query = "SELECT * FROM news WHERE contenuto LIKE :contenuto";
$query_params = array(
':contenuto' => $_POST['contenuto'] . '%'
);
You're mixing bind parameters with literals. Try this on for size:
$query = "SELECT * FROM news WHERE contenuto LIKE CONCAT(:contenuto, '%')";
Related
Lets say I have the following variable:
$where = "where `hats`='red'";
I want to inject this variable into a PDO statement. What is the proper way of doing this?
Is it like so?:
$sql = "select * from `clothing` :where";
$stm = $this->app->db->prepare($sql);
$stm->bindParam(':where', $where);
$stm->execute();
Any help would be greatly appreciated.
You can only bind values, not keywords, object names or syntactic elements. E.g., if you're always querying according to hats, you could bind the 'red' value:
$color = 'red';
$sql = "select * from `clothing` where hats = :color";
$stm = $this->app->db->prepare($sql);
$stm->bindParam(':color', $color);
$stm->execute();
If your where clause is really that dynamic, you'd have to resort to string manipulation (and face the risk of SQL injection, unfortunately):
$where = "where `hats`='red'";
$sql = "select * from `clothing` $where";
$stm = $this->app->db->prepare($sql);
$stm->execute();
// create a new PDO object by name $PDO in your connection file
In your function
function nameOfFunction($var,$value)
{
global $PDO;
$st=$PDO->prepare('SELECT * from clothing WHERE ? = ?');
$rs=$st->execute(array($var,$val));
return $st->fetchAll();
}
I hope it will work. It will return the array, Traverse it as you like
When I want to find a value from a row using PDO I use the following method:
//Search whether user exists
$sqlQueryEmailLogin = $dbh->prepare("SELECT vendor_id, first_name, last_name, email_login, user_password, passport_id, login_attempts, login_last_attempt FROM $tableVendorDetails WHERE email_login = ?");
$sqlQueryEmailLogin->bindValue(1, $emailLogin);
$sqlQueryEmailLogin->execute();
and the following PHP code for the search field
$emailLogin = 'xyz#abc.com'
Now I'd like to search two columns or more and use the following code
$sql = "SELECT * FROM articles WHERE id = ? AND status = ?";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, $id);
$stmt->bindValue(2, $status);
$stmt->execute();
I'd like to search the two columns from a string. How should I go about it, please?
The string value i go is from a html form with one input box
I'd like a string that is capable of searching two values from a MySQL table e.g.
$search = $id; and
$seach = $status;
in this case both cancel each other
You could simplify it by using the method described by #gbestard. But you should also do this:
$search = 'asdf'; // fill this with your form input
$sql = "SELECT * FROM articles WHERE id = :id OR status = :status";
$stmt = $conn->prepare($sql);
$stmt->execute(array(
':id' => $search,
':status' => $search,
));
Notice the change to OR in the query, and supplying the $search multiple times...
That's what I'm using
$sql = "SELECT * FROM articles WHERE id = :id AND status = :status";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':id' => $id , ':status' => $status));
Try the following
$sql = "SELECT * FROM articles WHERE id = :id AND status = :status";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':id', $id);
$stmt->bindValue(':status', $status);
$stmt->execute();
See docs http://php.net/manual/en/pdostatement.bindvalue.php
You should use OR instead of AND. That way, you will get all rows that match either by id or by status.
SELECT * FROM articles WHERE id = ? OR status = ?
I used to do :
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
I read that mysql statements are all deprecated and should not be used.
How can i do this with PDO?
The first line would be :
$stmt = $db->prepare("SELECT * FROM table WHERE id = " . $id); // there was an aditional double quote in here.
$stmt->execute(array(':id' => $id));
What about the mysql_fetch_assoc() function?
I am using php
You can use (PDO::FETCH_ASSOC) constant
Usage will be
while ($res = $stmt->fetch(PDO::FETCH_ASSOC)){
....
}
Here's the reference (documentation precisely) : http://www.php.net/manual/en/pdostatement.fetch.php
All well documentned in the manual: http://php.net/manual/en/pdostatement.fetchall.php
As example:
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>
There is a nice manual right here.
From which you can learn what you don't need to set fetch mode explicitly with every fetch.
...and even what with PDO you don't need no arrays at all to echo a number:
$stmt = $db->prepare("SELECT number FROM table WHERE id = ?");
$stmt->execute(array($id));
echo "Hello User, your number is".$stmt->fetchColumn();
This is a nice tutorial:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$stmt = $db->query("SELECT * FROM table");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($results);
?>
You can use PDO::FETCH_ASSOC for the same.
$stmt = $db->prepare("SELECT * FROM table WHERE id = :id");
$stmt->execute(array(':id' => $id));
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
while($record = $stmt->fetch()) {
//do something
}
You can find a good tutorial here
So I have two functions:
function display_name1($s){
global $db;
$query1 = "SELECT Taken From Alcohol where P_Key = $s";
$r = $db->prepare($query1);
$r->execute();
$result = $r->fetchColumn();
return $result;
}
function write_Recipe($s){
global $db;
$query1 = "SELECT Taken From Alcohol where Name = $s";
$r = $db->prepare($query1);
$r->execute();
$result = $r->fetchColumn();
return $result;
}
The only difference is that I'm matching the input "$s" with "P_Key" in the first example, and "Name" in the latter. When I put in a number for the first function, I get the appropriate return. When I put in a string that matches at least one "Name", I get nothing back. It seems to not be matches the strings for some reason. Any ideas?
There is a syntax error in the SQL query. You are missing the table name in the second query:
"SELECT Taken From where Name = '$s'"
Should be something like:
"SELECT Taken FROM `tablename` WHERE `Name` = '$s'"
Further note, that if you already using prepared statements, you should bind variables to the query instead of building the query using string concatination. Also the usage of global isn't perfect for an OOP design. Here comes an example how it can be done better:
// extend a class from PDO
class CustomPDO extends PDO {
public function display_name($s){
// use placeholder :p_key in query
$query1 = "SELECT Taken FROM `Alcohol` WHERE `P_Key` = :p_key";
$r = $this->prepare($query1);
// bind value to prepared statement
$r->execute(array(
':p_key' => $s
));
$result = $r->fetchColumn();
return $result;
}
public function write_recipe($s){
// use placeholder :name in query
$query1 = "SELECT Taken FROM `tablename` WHERE `Name` = :name";
// use $this as we are extended from PDO
$r = $this->prepare($query1);
// bind value to prepared statement
$r->execute(array(
':name' => $s
));
$result = $r->fetchColumn();
return $result;
}
}
Then use the class like a regular PDO object:
$db = new CustomPDO($connection_string, $user, $password);
But having two additional methods:
$result = $db->display_name('foo');
$result = $db->write_recipe('foo');
When querying on strings, you should surround a variable with quotes, like so:
"SELECT Taken From where Name = '$s'"
Also your second query is missing a table name.
"SELECT Taken FromTableNamewhere Name = '$s'"
Strings need to be quoted (and probably escaped if you haven't already). You seem to be using PDO, why not add a placeholder ? and execute execute(array($s)); instead, making PDO do the work for you?
function display_name1($s){
global $db;
$query1 = "SELECT Taken From Alcohol where P_Key = ?";
$r = $db->prepare($query1);
$r->execute(array($s));
$result = $r->fetchColumn();
return $result;
}
function write_Recipe($s){
global $db;
$query1 = "SELECT Taken From Alcohol where Name = ?";
$r = $db->prepare($query1);
$r->execute(array($s));
$result = $r->fetchColumn();
return $result;
}
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 />";
}