I want to check {if row exist} first and then fetch the results. here is my code:
$id = 102;
// connecting to database here
$sth = $dbh->prepare('SELECT * FROM users WHERE id = ?');
$sth->execute(array($id));
$num_rows = $sth->fetchColumn();
// if exist
if($num_rows){
// then fetch
while($end = $sth->fetch())
{
echo $end['id'];
}
}
But the output is blank, Why ?
It should be noted that the row with id = 102 is exist in the database.
As I understood, you have only one row with this ID. You can use fetch():
$id = 102;
// connecting to database here
$sth = $dbh->prepare('SELECT * FROM users WHERE id = ?');
$sth->execute(array($id));
$row = $sth->fetch();
// if record exist
if ($row) {
var_dump($row);
die();
}
PDO also have similar method rowCount but that would return effected rows in some cases.
Quoting from PHP Manual
For most databases, PDOStatement::rowCount() does not return the
number of rows affected by a SELECT statement. Instead, use
PDO::query() to issue a SELECT COUNT(*) statement with the same
predicates as your intended SELECT statement, then use
PDOStatement::fetchColumn() to retrieve the number of rows that will
be returned. Your application can then perform the correct action.
As suggested, you can query, count and proceed
$id = 102;
// connecting to database here
$sth = $dbh->prepare('SELECT COUNT(*) FROM users WHERE id = ?');
$sth->execute(array($id));
$num_rows = $sth->fetchColumn();
// if exist
if($num_rows > 0){
$sth = $dbh->prepare('SELECT * FROM users WHERE id = ?');
$sth->execute(array($id));
// then fetch
while($end = $sth->fetch())
{
echo $end['id'];
}
}
Related
I have a PDO select statement which executes successfully, rowCount is 1 but if I do fetchAll it returns []. Also fetch returns false.
Here's the code
$st = $this->prepareQuery(
"select table.* from table where
type = 'OFFER' and
active = true and
platform = ? and
id not in (select users_table. table id from users_table where users_table.user_id = ?)");
if($st->execute([$platform, $user["user_id"]])){
echo "success";
echo $st->rowCount(); // 1
echo json_encode($st->errorInfo()); //["00000",null,null]
echo json_encode($st->errorCode()); //00000
echo json_encode($st->fetchAll()); // []
echo json_encode($st->fetch()); // false
} else echo "failure";
return $st->fetchAll(PDO::FETCH_NAMED);
This works on local machine (MacOS php 7.3) but on production server(php 5.x).
That is because some database drivers with PDO have no natural row count function (rowCount() is only for INSERT, UPDATE or DELETE queries), so you have to use another method. Here is what I use:
$sql = 'select * from table';
$data = $PDO->query($sql);
$rows = $data->fetchAll();
$num_rows = count($rows);
So, based on your fetchAll() there are no actual rows.
I'm in the process of updating my old mysql database techniques to prepared pdo statements. I'm all good with while loops while($row = $result->fetch()) however how would I do the following with PDO prepared statements?
$sql = "SELECT * FROM table WHERE id=".$id;
$result = mysql_query($sql) or die(mysql_error());
$loop_count = mysql_num_rows($result);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = mysql_fetch_array($result);
echo $loop_row['field'];
}
I've tried this but with no joy:
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_count = $result->rowCount();
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = $result->fetch();
echo $loop_row['field'];
}
Thanks!
UPDATE: The reason for using a for loop instead of a while loop is the ability to paginate the results, otherwise I would just put LIMIT 7 on the end of the SQL query.
To properly count rows with PDO you have to do this -
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$rows = $result->fetch(PDO::FETCH_NUM);
echo $rows[0];
But you would be better off using LIMIT in your query if all you want to do is get a static number of results.
In addition you're making your loop overly complex, there is no need to test for a range in the for condition just set the static number unless you're doing something weird, like possibly pagination.
You can try it this way:
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_rows = $result->fetchAll();
$loop_count = count($loop_rows);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
echo $loop_rows[$row]['field'];
}
As requested by the OP, here's an example of PDO prepared statements using LIMIT and OFFSET for pagination purposes. Please note i prefer to use bindValue() rather than passing parameters to execute(), but this is personal preference.
$pagesize = 7; //put this into a configuration file
$pagenumber = 3; // NOTE: ZERO BASED. First page is nr. 0.
//You get this from the $_REQUEST (aka: GET or POST)
$result = $conn->prepare("SELECT *
FROM table
WHERE id= :id
LIMIT :pagesize
OFFSET :offset");
$result->bindValue(':id', $id);
$result->bindValue(':pagesize', $pagesize);
$result->bindValue(':offset', $pagesize * $pagenumber);
$result->execute();
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
This gives you the complete resultset of rows, limited to your required page. You need another query to calculate the total number of rows, of course.
What you could try is:
//Get your page number for example 2
$pagenum = 2;
//Calculate the offset
$offset = 7 * $pagenum;
//Create array
$data = array();
$result = $conn->prepare("SELECT * FROM table WHERE id= ? LIMIT 7 OFFSET ?");
$result->bind_param("ii", $id,$offset);
$result->execute();
$resultSet = $result->get_result();
while ($item = $resultSet->fetch_assoc())
{
$data[] = $item;
}
$result->close();
//echo resultSet you want
var_dump($data);
I need to get the number of rows of a studentID and then echo if the count is over 10.
This is what I wrote so far. But doesn't seem to work.
$findID = ID1231275;
$gipct = mysql_query("SELECT COUNT(studentID) FROM classFees WHERE studentID = '".$findID."'");
if ($gipct>10) {
echo ("$gipct");
}
$searchID = 'ID1231275';
$gipct = mysql_query("SELECT COUNT(studentID) as students FROM classFees WHERE studentID = '$searchID'");
$row = mysql_fetch_object($gipct);
if ($row->students >10) {
echo $row->students;
}
Btw, mysql_ functions are deprecated and can/will be removed in future versions of php, I recommend you to look at PDO statements or mysqli_ functions
$gipct is a mysql resource. So you have to use the function mysql_num_rows to get all rows that are selected.
Thats in your case not working because you have a COUNT in your query so you get only one row.
In your case you have to fetch the data first.
$gipct = mysql_query("SELECT COUNT(studentID) AS countout FROM classFees WHERE....");
$row = mysql_fetch_object($gpict);
if ($row->countout > 10) {
echo ("$gipct");
}
Or the method with the mysql_num_rows
$gipct = mysql_query("SELECT * FROM classFees WHERE student...");
if (mysql_num_rows($row) > 10) {
echo ("$gipct");
}
But here you select all records which can be much slower as the first solution.
If you are using php > 5 then you must use mysqli instead of mysql class. Then try this:
$db = new mysqli('localhost','user','pass','database');
$searchID = 'ID1231275';
$stmt = $db->prepare("SELECT COUNT(studentID) FROM classFees WHERE studentID =? ");
$stmt->bind_param('s', $searchID);
$stmt->execute();
$stmt->bind_result($gipct);
$stmt->fetch();
if ($gipct > 10) {
echo ($gipct);
}
I am using mysqli and php to be able to select a column from the database and to also be able to insert data into the database. Now while researching mysqli, I have found out that before checking to see if the number of rows equals to 0, I need to include a while($stmt->fetch()) {
Now because I have to blocks of code, one for SELECT and other INSERT, I want to know that does the while fetch loop suppose to wrap round the whole code or does it suppose to wrap round the SELECT block of code and INSERT block of code separately?
UPDATE:
$query = "SELECT TeacherAlias FROM Teacher WHERE TeacherAlias = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$getid);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbTeacherAlias);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
$results = $stmt->fetch_all();
foreach ($results as $row) {
if ($numrows == 0){
// don't use $mysqli->prepare here
$query = "SELECT TeacherUsername FROM Teacher WHERE TeacherUsername = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$getuser);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbTeacherUsername);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
$results = $stmt->fetch_all();
}
foreach ($results as $row) {
if ($numrows == 0){
// don't use $mysqli->prepare here
$query = "SELECT TeacherEmail FROM Teacher WHERE TeacherEmail = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$getemail);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbTeacherEmail);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
$results = $stmt->fetch_all();
}
}
}
}
Try mysqli::fetch_all(), which returns an associative array:
$results = $stmt->fetch_all();
foreach ($results as $row) {
// do something...
}
// if no results found it will return either empty array or null (not sure, check it)
$results = $stmt->fetch_all();
// if $results is an empty array it will not enter the loop
foreach($results as $row) {
if ($numrows == 0){ // this is never reached if results no results were found
In the past I would do something like so:
$sql = 'SELECT * FROM customers WHERE customer_email="' . mysql_real_escape_string($_POST['customer_email']) . '" ';
$res = mysql_query($sql);
// if there are no hits...
if(mysql_num_rows($res) == FALSE) {
Today I am doing the same thing however with prepared statements:
$stmt = $dbh->prepare("SELECT * FROM customers where customer_email = ? LIMIT 1");
if ($stmt->execute(array($_POST['customer_email']))) {
The 2nd line of my prepared statement if($stmt... is that "if this query gets a result" or is it "if this query is executed regardless of results or not ie if it executes without error".
What I'm trying to work out is with prepared statements how do you do the equivalent of mysql_num_rows() == FALSE?
Thanks!!
You can use the rowCount() method of PDOStatement to get the number of rows returned:
$stmt = $dbh->prepare("SELECT * FROM customers where customer_email = ? LIMIT 1");
$stmt->execute(array($_POST['customer_email']));
if($stmt->rowCount() > 0) {
//fetch stuff...
}
Or, if rowCount() proves to be unreliable, you can do this:
$all = $stmt->fetchAll();
if(count($all)) {
//loop through the set...
}
PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement and not the number of rows returned by select query,
for select query I use :
fetchAll(PDO::FETCH_OBJ);
And
echo count($lignes);
<?php
$PARAM_hote='localhost';
$PARAM_port='3306';
$PARAM_db='test';
$PARAM_user='root';
$PARAM_pwd='';
try
{
$connexion = new PDO('mysql:host='.$PARAM_hote.';dbname='.$PARAM_db, $PARAM_user,$PARAM_pwd);
}
catch(Exception $e)
{
echo 'Erreur : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
}
$requete_prepare_1=$connexion->prepare("SELECT * FROM `test_mysql`");
$requete_prepare_1->execute();
$lignes=$requete_prepare_1->fetchAll(PDO::FETCH_OBJ);
echo count($lignes);
?>