I have a question related to php / pdo and sqlite. I have ported some code from a mysql backend to a sqlite backend. I have used rowCount() alot in this project.
In my original Mysql application i did this:
$stmt = $db->query("SELECT id FROM table where id = $id ");
$rc = $stmt->rowCount();
if ($rc == 1) {
// do something
}
The documentation says this method is only for returning affected rows from UPDATE, INSERT, DELETE queries, with the PDO_MYSQL driver (and this driver only) you can get the row count for SELECT queries.
So, how to achive the same thing with a sqlite backend?
This is how I have ended up doing it:
$stmt = $db->query("SELECT count(id) as cnt FROM table where id = $id ");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($row['cnt'] == "1") {
// do something
} else {
return false;
}
}
}
I am looking for a more elegant solution, while achieving the same thing as rowCount().
This is the way to do that in pdo:
$stmt = $db->query('SELECT * FROM table');
if ($stmt->rowCount() == 1) {
//...
} else {
//...
}
echo $row_count.' rows selected';
(The same way XD)
BTW, I wouldn't recommend doing something like
$stmt = $db->query("SELECT count(id) as cnt FROM table where id = $id ");
It's not good to have variables in statements like that. use something like:
$stmt = $db->query('SELECT id FROM table where id = ?');
$stmt->execute(array($id));
if ($stmt->rowCount() == 1)
{
$arr = $stmt->fetch(PDO::FETCH_ASSOC);
foreach($arr as $element)
{
echo '<pre>'.print_r($element).'</pre>';
}
}
else
{
//...
}
This is part of some code I'm using:
$stmt = $db->prepare('SELECT * FROM users WHERE id=?');
$stmt->execute(array($id));
if ($stmt->rowCount() == 1) {
$currentUser = $stmt->fetchAll(PDO::FETCH_ASSOC)[0];
} else {
return false;
}
Edit: (for compatibility issues)
$stmt = $db->query('SELECT * FROM table');
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (($arr === false) || (sizeof($arr) == 0)) {
return false;
} else {
//... do ....
echo sizeof($arr);
}
Related
I need help with converting this SQL to Prepared Statement. This is for my search bar. I hope I'll be able to receive some help as I am a beginner in this.
This is my SQL
$conn = mysqli_connect('localhost','root','','my_db');
$mysql = "SELECT * FROM catetable";
$bike_list = mysqli_query($conn,$mysql);
$catesql = "SELECT catename FROM catetable";
$cate_list = mysqli_query($conn,$catesql);
And this is what I would like to change to Prepared Statement
if (isset($_GET['search']))
{
$search = $_GET['search'];
$searchlist = array();
$lowersearchlist = array();
$i = 0;
while ($one_cate = mysqli_fetch_assoc($cate_list))
{
$searchlist[$i] = $one_cate['catename'];
$lowersearchlist[$i] = strtolower($one_cate['catename']);
$i++;
}
if (in_array($search,$searchlist) || in_array($search,$lowersearchlist))
{
header("Location:feature.php");
}
else
{
header("Location:index.php?error=true");
}
}
Write a query that matches the parameter in the WHERE clause. MySQL normally defaults to case-insensitive comparisons, so you don't need to fetch all the rows to compare them exactly and case-insensitively.
if (isset($_GET['search'])) {
$stmt = $conn->prepare("SELECT COUNT(*) AS c FROM yourTable WHERE catename = ?");
$stmt->bind_param("s", $_GET['search']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($row['c'] > 0) {
header("Location: feature.php");
} else {
header("Location: index.php?error=true";
}
}
I use this code to get rows from database.
// Prepare WC statement
$queryUP = $pdo->prepare("SELECT * FROM unitprices WHERE id_quot = :idQuotation");
// Execute Unit prices statement
$queryUP->execute(array(
'idQuotation' => $idQuotation
));
// How to check the results is empty or not ?
if (results) {
// foreach($queryUP as $rowup) {
//...
// }
} else {
// do another thing
}
I don't how to do to check if there is some results in the query before continuing the code ?
$queryUP = $pdo->prepare("SELECT * FROM unitprices WHERE id_quot = ?");
$queryUP->execute(array($idQuotation));
//here you go
$results = $queryUP->fetchAll();
if ($results) {
// foreach($results as $rowup) {
//...
// }
} else {
// do another thing
}
Hope you are doing your foreach in the template, not right in place as shown here.
If your memory allows you, you can fetch all:
$queryUP = $pdo->prepare("SELECT * FROM unitprices WHERE id_quot = :idQuotation");
$queryUP->bindParam(':idQuotation', $idQuotation, PDO::PARAM_STR);
$queryUP->execute();
$result = $queryUP->fetchAll(PDO::FETCH_ASSOC);
if (count($result) > 0) {
} else {
}
I'm switching from MySQL to PDO and I'm unsure if this query is correct.. would I still be required to write the if command.
public function User_Login($_iUsername,$_iPassword) {
$username=mysql_real_escape_string($_iUsername);
$password=mysql_real_escape_string($password);
$md5_password=md5($_iPassword);
$query=mysql_query("SELECT _iD FROM users WHERE _iUsername='$_iUsername' and _iPassword='$md5_password' AND _iStatus='1'");
if( mysql_num_rows( $query ) == 1 ) {
$row = mysql_fetch_array( $query );
return $row['_iD'];
} else {
return false;
}
}
TO
public function User_Login($_iUsername,$_iPassword) {
$md5_password = md5($_iPassword);
$sth = $db->prepare("SELECT _iD FROM users WHERE _iUsername='$_iUsername' and _iPassword='$md5_password' AND _iStatus='1'");
$sth->execute();
$result = $sth->fetchAll();
}
First off, you're not properly parameterizing the query. It's great that you're using PDO, but one of the main purposes of the change is the ability to parameterize queries. Secondly, md5 is a very weak hash. I suggest using bcrypt instead. Finally, PDOStatement::rowCount is the method you are looking for.
$sth = $db->prepare("SELECT _ID FROM users WHERE _iUsername = ?
AND _iPassword = ? AND _iStatus = 1");
$sth->execute(array($_iUsername, $md5_password));
if ($sth->rowCount() == 1) {
$row = $sth->fetch(PDO::FETCH_ASSOC);
return $row['_iD'];
}
else {
return false;
}
This question already has an answer here:
How to check fetched result set is empty or not?
(1 answer)
Closed 11 months ago.
What am I doing wrong here? I'm simply retrieving results from a table and then adding them to an array. Everything works as expected until I check for an empty result...
This gets the match, adds it to my array and echoes the result as expected:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today', $today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
return true;
When I try to check for an empty result, my code returns 'empty', but no longer yields the matching result:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today',$today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
if ($sth->fetchColumn()) {
echo 'not empty';
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
return true;
}
echo 'empty';
$db = null;
return false;
You're throwing away a result row when you do $sth->fetchColumn(). That's not how you check if there are any results. You do
if ($sth->rowCount() > 0) {
... got results ...
} else {
echo 'nothing';
}
Relevant documentation is here: PDOStatement::rowCount
If you have the option of using fetchAll() then, if there are no rows returned, it will just be an empty array.
count($sql->fetchAll(PDO::FETCH_ASSOC))
will return the number of rows returned.
You should not use rowCount for SELECT statements as it is not portable. I use the isset function to test if a select statement worked:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
// I would usually put this all in a try/catch block, but I kept it the same for continuity
if(!$sth->execute(array(':today'=>$today)))
{
$db = null;
exit();
}
$result = $sth->fetch(PDO::FETCH_OBJ)
if(!isset($result->id_email))
{
echo "empty";
}
else
{
echo "not empty, value is $result->id_email";
}
$db = null;
Of course this is only for a single result, as you might have when looping over a dataset.
I thought I would weigh in as I had to deal with this lately.
$sql = $dbh->prepare("SELECT * from member WHERE member_email = '$username' AND member_password = '$password'");
$sql->execute();
$fetch = $sql->fetch(PDO::FETCH_ASSOC);
// if not empty result
if (is_array($fetch)) {
$_SESSION["userMember"] = $fetch["username"];
$_SESSION["password"] = $fetch["password"];
echo 'yes this member is registered';
}else {
echo 'empty result!';
}
what I'm doing wrong here?
Almost everything.
$today = date('Y-m-d'); // no need for strtotime
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today',$today); // no need for PDO::PARAM_STR
$sth->execute(); // no need for if
$this->id_email = $sth->fetchAll(PDO::FETCH_COLUMN); // no need for while
return count($this->id_email); // no need for the everything else
Effectively, you always have your fetched data (in this case in $this->id_email variable) to tell whether your query returned anything or not. Read more in my article on PDO.
One more approach to consider:
When I build an HTML table or other database-dependent content (usually via an AJAX call), I like to check if the SELECT query returned any data before working on any markup. If there is no data, I simply return "No data found..." or something to that effect. If there is data, then go forward, build the headers and loop through the content, etc. Even though I will likely limit my database to MySQL, I prefer to write portable code, so rowCount() is out. Instead, check the the column count. A query that returns no rows also returns no columns.
$stmt->execute();
$cols = $stmt->columnCount(); // no columns == no result set
if ($cols > 0) {
// non-repetitive markup code here
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
I only found one way that worked...
$quote = $pdomodel->executeQuery("SELECT * FROM MyTable");
//if (!is_array($quote)) { didn't work
//if (!isset($quote)) { didn't work
if (count($quote) == 0) { //yep the count worked.
echo 'Record does not exist.';
die;
}
Thanks to Marc B's help, here's what worked for me (note: Marc's rowCount() suggestion could work too, but I wasn't comfortable with the possibility of it not working on a different database or if something changed in mine... also, his select count(*) suggestion would work too, but, I figured because I'd end up getting the data if it existed anyway, so I went this way).
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today', $today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
if (count($this->id_email) > 0) {
echo 'not empty';
return true;
}
echo 'empty';
return false;
This is the login function written using MySQL way
However, the problem exists when it convert into PDO way
MYSQL:
<?
function confirmUser($username, $password){
global $conn;
if(!get_magic_quotes_gpc()) {
$username = addslashes($username);
}
/* Verify that user is in database */
$q = "select UserID,UserPW from user where UserID = '$username'";
$result = mysql_query($q,$conn);
if(!$result || (mysql_numrows($result) < 1)){
return 1; //Indicates username failure
}
/* Retrieve password from result, strip slashes */
$dbarray = mysql_fetch_array($result);
$dbarray['UserPW'] = stripslashes($dbarray['UserPW']);
$password = stripslashes($password);
/* Validate that password is correct */
if($password == $dbarray['UserPW']){
return 0; //Success! Username and password confirmed
}
else{
return 2; //Indicates password failure
}
}
PDO:
<?
function confirmUser($username, $password){
global $conn;
include("connection/conn.php");
$sql = '
SELECT COALESCE(id,0) is_row
FROM user
WHERE UserID = ?
LIMIT 1
';
$stmt = $conn->prepare($sql);
$stmt->execute(array('09185346d'));
$row = $stmt->fetch();
if ($row[0] > 0) {
$sql = '
SELECT COALESCE(id,1) is_row
FROM user
WHERE UserPW = ?
LIMIT 1
';
$stmt = $conn->prepare($sql);
$stmt->execute(array('asdasdsa'));
$row = $stmt->fetch();
if ($row[0] > 0)
return 2;
else
return 0;
}
elseif ($row[0] = 0)
{return 1;}
}
What is the problem ?? And is it necessary to include bind parameter in PDO??? THANKS
Aside from your use of global and your include inside the function (you should investigate an alternative way of structuring your function not to do this), I would change the code as follows:
$sql =
'SELECT id
FROM user
WHERE UserID = ?
AND UserPW = ?
LIMIT 1';
$stmt = $conn->prepare($sql);
$stmt->execute(array(
'09185346d',
'asdasdsa'
));
if ($stmt->rowCount() == 1) {
return 0;
}
else {
return 1;
}
Combing the queries to give a general Authentication error, instead of allowing people to trial valid usernames, and then valid passwords, and then using PDOStatements rowCount method do see if your row was returned.
To answer your second part, it is not necessary to specifically use bindParam to prevent SQL injection.
Here's a quick example of the difference between bindParam and bindValue
$param = 1;
$sql = 'SELECT id FROM myTable WHERE myValue = :param';
$stmt = $conn->prepare($sql);
Using bindParam
$stmt->bindParam(':param', $param);
$param = 2;
$stmt->execute();
SELECT id FROM myTable WHERE myValue = '2'
Using bindValue
$stmt->bindValue(':param', $param);
$param = 2;
$stmt->execute();
SELECT id FROM myTable WHERE myValue = '1'