I have an SQL table for a gallery, it has rows for id, userid, imagename.
I'm trying to write a function that calculates how many images a certain user has added, I'm new to PDO and SQL. This is what I have for my function;
// Photo Count
public function photoCount($id){
$this->db->query('SELECT * FROM gallery WHERE id = :id');
// Bind value
$this->db->bind(':id', $id);
$row = $this->db->single();
// Check row
$count = $this->db->rowCount();
return $count;
}
Do I need the line $row = $this->db->single(); or can I just return the rowCount at the moment all is being returned is 0's which is incorrect.
Any help appreciated.
Use SQL count function. If $this->db is a PDO object then...
public function photoCount($id){
$statement = $this->db->prepare('SELECT count(*) as c FROM gallery WHERE id = :id');
$statement->bindParam(":id", $id);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_OBJ);
return $result->c;
}
Related
I am new to php and trying hard to learn its why you guys and gals need to Forgive me for asking a lot!
Here is my question;
I am trying to call a function with where clause multiple times, I have read allmost all posts and examples still didn't understand how to do it.
I tought that An example will be more useful than any blurb I can write.
Here is the function I am trying to create and use it multiple times :
function getTable($tableName, $clause) {
$stmt = $pdo->prepare("SELECT * FROM ".$tableName." WHERE ".$clause." = :".$clause);
$stmt->bindParam(":$clause", $clause, PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount() > 0){
return true;
}else{
return false;
}
return $stmt;
}
I am not sure if my fucntion is safe or its rigth.
AND this is how I am trying to call function, which I dont know how to call table name and where clause and how to turn while loop.
getTable('posts');
If you give an example of creating and caling function, I would be grateful, Thanks
Nope, your function is not safe. Moreover it is just useless. There is no use case where you would use it like this getTable('posts');. And for the everything else it is much better to allow the full SQL syntax, not some limited subset.
The simplest yet most powerful PDO function I can think of is a function that accepts a PDO object, an SQL query, and array with input variables. A PDO statement is returned. I wrote about such function in my article about PDO helper functions. So here is the code:
function pdo($pdo, $sql, $args = NULL)
{
if (!$args)
{
return $pdo->query($sql);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
}
With this function you will be able to run any query, with any number of WHERE conditions, and get results in many different formats. Here are some examples from the article mentioned above:
// getting the number of rows in the table
$count = pdo($pdo, "SELECT count(*) FROM users")->fetchColumn();
// the user data based on email
$user = pdo($pdo, "SELECT * FROM users WHERE email=?", [$email])->fetch();
// getting many rows from the table
$data = pdo($pdo, "SELECT * FROM users WHERE salary > ?", [$salary])->fetchAll();
// getting the number of affected rows from DELETE/UPDATE/INSERT
$deleted = pdo($pdo, "DELETE FROM users WHERE id=?", [$id])->rowCount();
// insert
pdo($pdo, "INSERT INTO users VALUES (null, ?,?,?)", [$name, $email, $password]);
// named placeholders are also welcome though I find them a bit too verbose
pdo($pdo, "UPDATE users SET name=:name WHERE id=:id", ['id'=>$id, 'name'=>$name]);
// using a sophisticated fetch mode, indexing the returned array by id
$indexed = pdo($pdo, "SELECT id, name FROM users")->fetchAll(PDO::FETCH_KEY_PAIR);
Special for you, here is the while example, though this method is considered clumsy and outdated:
$stmt = pdo($pdo,"SELECT * FROM tableName WHERE field = ?",[$value]);
while ($row = $stmt->fetch()) {
echo $row['name'];
}
I try to translate this query to my PDO object from this thread:
UPDATE table_name
SET col1 = <<new value>>,
col2 = <<new values>>,
last_modified_timestamp = <<new timestamp>>
WHERE primary_key = <<key column>>
AND last_modified_timestamp = <<last modified timestamp you originally queried>>
So i have a "modified" field in the mysql table and fetch the data (SELECT modified AS last_modified) to pre-fill in a hidden field in my form and post the value to the object:
$position->readOne();
$position->last_modified = $_POST['last_modified'];
<input name='last_modified' value='{$position->last_modified}'>
My object update query looks like:
UPDATE positions
SET
... some values ...
WHERE id=:id
AND modified=:last_modified
$stmt->bindParam(":last_modified", $this->last_modified);
If I check the posted variables, everything looks fine but the update query ignores my second where clause completely and override the modified field after post the form.
Sure a beginner issue but I canĀ“t find it.
Thanks
EDIT:
Select query
public function readOne(){
$query = "SELECT
p.position,
p.modified,
p.modified AS last_modified
FROM positions p
WHERE id = ?
LIMIT 0,1";
$stmt = $this->conn->prepare( $query );
$stmt->bindParam(1, $this->id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$this->position = $row['position'];
$this->modified = $row['modified'];
$this->last_modified = $row['last_modified'];
}
Update query
public function updatePosition(){
$this->getTimestamp();
$query = "UPDATE positions
SET
position=:position,
modified=:modified,
WHERE id=:id
AND modified=:last_modified";
$stmt = $this->conn->prepare($query);
$this->position=htmlspecialchars(strip_tags($this->position));
$stmt->bindParam(":id", $this->id);
$stmt->bindParam(":position", $this->position);
$stmt->bindParam(":modified", $this->timestamp);
$stmt->bindParam(":last_modified", $this->last_modified);
if($stmt->execute()){
print_r($this->last_modified);
return true;
}
print_r($stmt->errorInfo());
return false;
}
public function getTimestamp(){
date_default_timezone_set('Europe/Berlin');
$this->timestamp = date('Y-m-d H:i:s');
}
I figured it out. The update query and everything else worked fine but the problem was the notification handling, so the function updatePosition() told me everything was updated but it worked as it should and it did not update anything if the value was not the same.
This fixed it:
if($stmt->execute()){
$affected_rows = $stmt->rowCount();
if ($affected_rows == 1) {
return true;
}
This helped me to understand how it works ... PDOStatement::execute() returns true but the data is not updated
I'm currently going thorough a site and replacing all the functions which used to return mysql_fectch_array() results, which are put into while loops elsewhere. I'm trying to make them return the same data in the same format but by using mysqli prepared statements output. I have been successful with the code below in producing the same formatted output for single row results.
public function get_email_settings(){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT * FROM email_setting WHERE user_id = ? LIMIT 1");
$stmt->bind_param("i", $this->user);
$stmt->execute();
$stmt->bind_result(
$row['email_id'],
$row['user_id'],
$row['news'],
$row['new_message'],
$row['new_friend'],
$row['rule_assent'],
$row['agreement_ready'],
$row['agreement_all_assent'],
$row['time_cap'],
$row['donations']
);
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $row;
}
But how can I get this code to work when it returns more than one row? I want it to be produce the same result as if I had written:
return mysql_fetch_array($result);
Is it possible?
Consider the following adjustment, passing query results into an associative array:
public function get_email_settings(){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT email_id, user_id, news, new_message,
new_friend, rule_assent, agreement_ready,
agreement_all_assent, time_cap, donations
FROM email_setting
WHERE user_id = ? ");
$stmt->bind_param("i", $this->user);
$stmt->execute();
// CREATE RETURN ARRAY
$row = [];
// OBTAIN QUERY RESULTS
$result = $stmt->get_result();
// ITERATE THROUGH RESULT ROWS INTO RETURN ARRAY
while ($data = $stmt->fetch_assoc()) {
$row[] = $data;
}
$stmt->close();
return $row;
}
You will notice I explicitly select the query's fields to avoid an indeterminate loop through query results.
Ok I have managed to get it to work without using get_result()
This is how I did it with alot of help from Parfait and Example of how to use bind_result vs get_result
function saved_rules($user){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT R.rule_id, R.rule_title
FROM Savedrules S
LEFT JOIN Rule R
ON S.saved_rule_id = R.rule_id
WHERE S.saved_user_id = ?");
$stmt->bind_param("i", $user);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $rule_title);
while ($stmt->fetch()) {
$result[] = Array("rule_id"=>$id,"rule_title"=>$rule_title);
}
$stmt->free_result();
$stmt->close();
return $result;
}
Its not exactly the same output as using a mysql_fetch_array() so where it is used I have to change the loop to:
foreach($saved_rules AS $row){}
from
while ($row = mysql_fetch_array($saved_rules){}
This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
Closed 9 years ago.
I want to get all the list of registered players from an array
here is my function
function UpdateContact()
{
try {
$conn = $this->GetDBConnection();
$linkedInId = trim($_REQUEST['linkedInId']);
$statement = $conn->prepare('UPDATE users SET linkedInId = :linkedInId WHERE linkedInId = :linkedInId');
$statement->bindParam(':linkedInId', $linkedInId, PDO::PARAM_STR);
$statement->execute();
//$updatedTime = time() - 120;
$ids = implode(",",$_POST['ids']);
// $ids = (abc,def,geh,ijk,lac);
$statement = $conn->prepare('SELECT * FROM users WHERE linkedInId IN (:ids)');
$statement->execute($ids);
$conn = null;
if (!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
return false;
else
return $row;
} catch(PDOException $e) {
throw $e;
}
}
Just return false
Maybe because i am not able to bind the array with PDO Statement?
How can I fix this solution, i might want to add more binding parameters too later on, so i don't want to do execute($ids) either.
I have tried bindParam(':ids',$ids) too but of no avail
$items = array();
//$statement->bindParam(':updatedTime', $updatedTime, PDO::PARAM_STR);
foreach ($id as $ids)
{
$statement = $conn->prepare('SELECT * FROM users WHERE id = :id');
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
if(($row = $statement->fetch(PDO::FETCH_OBJ)))
$items[] = $id;
}
I think it would make more sense to parse the array/list and perform the select for each id in the array/list.
Pseudo code:
init resultArray;
For x in List
select * from database where ids =: x
if result
add result to resultArray
return resultArray
But that's just the basic way of doing it, I'm not sure if you can do it more advanced.
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 />";
}