I know how to fetch a PDO array, but how do I collect data from it like you do with MySQLi's fetch_array?
For example,
MySQLi
$query = $mysqli->query("SELECT * FROM `foo` WHERE `ID`='1'");
$array = $query->fetch_array();
Getting a result
echo $array['bar'];
How would you do this with PDO? I understand you can do this:
PDO
$query = $pdo->prepare("SELECT * FROM `foo` WHERE `ID`='1'");
$query->execute();
$result = $query->fetchAll();
Getting the result
echo $result['bar'];
Does not return the same as MySQLi did
Am I doing something wrong, and is there a way of doing this?
fetchAll() is not the same as fetch_array().
You want fetch() to get one row, not fetchAll() which gets ALL rows.
$result = $query->fetch(PDO::FETCH_ASSOC);
Related
I want an if-statement that only runs, when there are no rows in the table or if existing rows dont match a specific parameter from my input. I tried this way:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = '$currentURL'";
$result = $conn->query($sql);
if(!$result)
{ ... }
From my thinking this should execute the if-statement on the first time I want to add something to the database and if the $currentURL does not exist in existing data. But this does not seem to work the way I think it does. How would you do this? Maybe I'm handling the $result wrong, because if I test the sql-query inside phpmyadmin this shows the right result (no rows).
The correct way to do this would be to use prepared statement and fetch the results into an array. You can fetch all rows into an array using fetch_all()
$stmt = $conn->prepare("SELECT * FROM images WHERE imageURL = ?");
$stmt->bind_param('s', $post["media_url"]);
$stmt->execute();
// Get result and then fetch all rows from the result object
$result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
// Then check if you have any rows at all using a simple if statement
// Negate it using ! to check if the array is empty
if (!$result) {
// no results found
}
I guess, that $conn is a PDO connection? In that case, the method $conn->query() returns an object of type PDOStatement. See https://www.php.net/manual/de/class.pdostatement.php
The method does NOT return the result set.
Instead you can use the PDOStatement object, to fetch the results:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = '$currentURL'";
$result = $conn->query($sql)->fetchAll();
if(empty($result))
{ ... }
In case you are using mysqli, the object returned by query() is this: https://www.php.net/manual/en/class.mysqli-result.php
So the code would be:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = '$currentURL'";
$result = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);
if(empty($result))
{ ... }
Please also note: Your code is highly insecure! You should use prepared statements to prevent sql-injection:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = :currentUrl";
$stmt = $conn->prepare($sql);
$stmt->execute(['currentUrl' => $currentURL]);
$result = $stmt->fetchAll();
if(empty($result))
{ ... }
sanitize input against sql injection (or better - use prepared statements and param binding)
$sql = "SELECT * FROM images WHERE imageURL = '".$conn->real_escape_string($currentURL)."'";
mysqli query returns true on success (even empty dataset is success), use num_rows instead:
if ( $result->num_rows === 0 ) { ... }
I have a problem with a simple pdo query here the query:
$NU=$connection->exec("SELECT COUNT(ID) AS Total FROM USERS");
$Result=$NU->fetch(PDO::FETCH_ASSOC)['Total'];
echo "$Result";
Since I have no params to bind in the query is correct to use exec without prepare, and how can I fix this problem? (Call to a member function fetch() on integer in )
The exec() method only returns the number of rows effected. You probably want to use query() instead.
$NU=$connection->query("SELECT COUNT(ID) AS Total FROM USERS");
$Result=$NU->fetch(PDO::FETCH_ASSOC)['Total'];
echo "$Result";
The query() statement will execute a single query and return a PDOStatement object you can fetch from or false on failure.
You need to use query http://php.net/manual/en/pdo.query.php , then you'll have a object with results you can work with.
Try this.
$NU = $connection->query("SELECT COUNT(ID) AS Total FROM USERS");
$result = $NU->fetch();
echo $result['Total'];
What you are looking for is not exec but prepare. From the PHP doc: http://php.net/manual/en/pdostatement.fetch.php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
i'm trying to retrieve info from my database using PDO.
The code i'm using is
$input = $_GET['input'];
$inputvalue = $_GET['inputvalue'];
$db = DB::get_instance();
$query = $db->prepare('SELECT * FROM hwidex7 WHERE :input=:inputvalue');
$query->bindParam(':inputvalue', $inputvalue);
$query->bindParam(':input', $input);
$query->execute();
You can't bind table or column as parameter in PDO
You can build your query as
$query = $db->prepare("SELECT * FROM hwidex7 WHERE `$input` =:inputvalue");
$query->bindParam(':inputvalue', $inputvalue);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
print_r($result);
Both ways are wrong.
SELECT * FROM hwidex7 WHERE `HWID`='3087793810'
Just try above query.
You will get Idea for same.
Hello I have a prepared statement and I need to count the number of results I get. In order to do this I use store_result and num_rows
$query = 'SELECT userId, promo, email FROM users WHERE active = ?';
$rsActivation = $db->prepare($query);
$rsActivation->bind_param('s', $actv);
$rsActivation->execute();
$rsActivation->store_result();
$totalRows = $rsActivation->num_rows;
This code manages to get me the number of rows. The problem is that if I do this I cannot use fetch() on $rsActivation. If I use fetch and not use store_result I cannot get the number of rows.
How can I accomplish both things?
Thanks
SOLVED:
Turns out my problem was I was trying to fetch the results as an associative array. Instead I used bind_result to assign values to variables. Then I was able to use store_result and num_rows to get the count and after that I used fetch() together with the variables I assigned in bind_result.
$query = 'SELECT userId, promo, email FROM users WHERE active = ?';
$rsActivation = $db->prepare($query);
$rsActivation->bind_param('s', $actv);
$rsActivation->execute();
$rsActivation->bind_result($userId, $promo, $email);
$rsActivation->store_result();
$totalRows = $rsActivation->num_rows;
while($rsActivation->fetch()){
echo "<p>". $userId ."</p>";
...
}
You can try using
...
$rsActivation->execute();
$results = $rsActivation->get_results();
$totalRows = $results->num_rows;
and you should be able to fetch using something like
$results->fetch_assoc(), $results->fetch_row(), etc.
Here's the doc for it: http://php.net/manual/en/class.mysqli-result.php
I am trying to get variable from pdo query but I got an error and could not figure it out. Error I get is PDO::query() expects parameter 1 to be string, object given.
// first I get variable, and when I echo variable I get good result.
$id=$_POST("kolicina");
$stmt=$conn->prepare("SELECT Kolicina FROM table1 where Kolicina=$id");
$q=$conn->query($stmt);
while($row = $q ->fetch(PDO::FETCH_ASSOC)){
$kolicina=$row["Kolicina"];
}
echo $kolicina;
Use instead:
id=$_POST("kolicina");
$stmt=$conn->prepare("SELECT Kolicina FROM table1 where Kolicina=:id");
$stmt->execute(array('id' => $id));
the :id is binded to $id on the execute statement.
And to fetch the result use:
$stmt->fetch(PDO::FETCH_ASSOC);
First read here PHP MANUAL PDO
Second what you did there is wrong.
$id = $_POST['yourvarfromform'];
$stmt = $conn->prepare("SELECT * FROM table1 WHERE Kolicina = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_STR) // if it's string you can check on pdo manual because you can use int and others.
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $key => $value {
// Run Some Code Here
}
Change your code to be like this:
$stmt=$conn->prepare('SELECT Kolicina FROM table1 where Kolicina = :id');
$array = array('id' => $id);
$stmt->execute($array);
And you can fecth all results like this:
$result = $stmt->fetchAll();
print_r($result);
?>