I want to be able to translate the mysql code below into PDO equivalent. Please can someone help me out as I have looked around and tried other examples but they are not working for me.
// Count Participants
$result = mysql_query("SELECT * FROM table2");
$num_rows = mysql_num_rows($result);
You can either just issue a count query to the DB
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$count = $db->query('SELECT count(*) FROM table2')->fetchColumn();
or get an array back that can be counted
$stmt = $db->query('SELECT * FROM table2');
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = count( $rows );
or get any kind of other resultset back, and count that etc.
Related
I got the following sql:
SELECT COUNT(pu_id) FROM purchasing WHERE MONTH(pu_create_date)=MONTH(NOW())
In Mysql it gives the result 0 as expected.
When I put it in PHP I get the result 1 of $numMonth. This is the php code:
$database = new Database();
$db = $database->getConnection();
$stmt= $db->query('SELECT COUNT(pu_id) FROM purchasing WHERE MONTH(pu_create_date)=MONTH(NOW())') ;
$numMonth = $stmt->execute();
echo $numMonth;
Why do I get two different results?
pu_id = unique key
pu_create_date = timestamp
You have to fetch the row from the query.
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_NUM);
$numMonth = $row[0];
echo $numMonth;
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 know that inside MySQL, you can use:
SELECT COUNT(*) FROM table
I have written the following code in PHP to display the number of rows on the page:
$sql = 'select * from users';
$data = $conn -> query($sql);
echo $data;
But when I run it, I get the following error:
Catchable fatal error: Object of class PDOStatement could not be converted to string in [Directory] on line 19.
I think the problem is that the returned value is not in string form. If that is correct, how would I be able to display the number of rows on the page?
If you want to count the rows you can do this with PDO:
$sql = 'select * from users';
$data = $conn->query($sql);
$rows = $data->fetchAll();
$num_rows = count($rows);
Well, you arent badly off, you are almost there:
$sql = 'SELECT COUNT(*) as numrow FROM users';
$data = $conn -> query($sql);
rows = $data->fetchAll();
Depending on the type of return data, you could use
$rows->numrow if the return data is an object
There are some easy and faster way to do this
COUNT the column in query and fetch
$sql = "SELECT COUNT(id) AS total_row FROM table_name";
$stmt = $conn->query($sql);
$stmt->execute();
echo $count['total_row'];
Using rowCount()
$sql = "SELECT * FROM table_name";
$stmt = $conn->query($sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count;
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 have a table in my database named visitor_table . Within table i have a column named visitor_affiliate. I want to get the count of the rows when visitor_affiliate = "someurer" .
I want to get the count as number. I already have this code but i don't know how to get the count only for the rows containing the string. I currently get the number of all rows,
$result = mysql_query("SELECT * FROM visitor_table");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
You can ask MySQL to return the count:
SELECT COUNT(*) FROM visitor_table WHERE visitor_affiliate = 'someurer'
You shouldn't be using the ancient (deprecated as of PHP v5.5.0, soon to be removed entirely) MySQL extension for writing new codeāuse instead the improved MySQLi extension or the PDO abstraction layer, both of which enable you to pass variables to the database in a safe, parameterised, fashion that ensures they are not evaluated for SQL (and therefore prevents SQL injection attacks):
$dbh = new PDO("mysql:dbname=$dbname", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$qry = $dbh->prepare('
SELECT COUNT(*) FROM visitor_table WHERE visitor_affiliate = ?
');
$qry->execute(['someurer']);
echo $qry->fetchColumn(), ' rows';
$result = mysql_query("SELECT * FROM visitor_table WHERE `visitor_affiliate` = 'someurer'");
$num_rows = mysql_num_rows($result);
echo $num_rows . " Rows\n";
With what little information you have given just try this-
$result = mysql_query("SELECT * FROM visitor_table Where visitor_affiliate like '%someurer%'");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
The deprecated MySQL:
$res = mysql_query('SELECT * FROM visitor_table');
echo 'Number of rows:'.mysql_num_rows($res);
Procedural MySQLi:
$tu = mysqli_prepare($DBH,'SELECT * FROM visitor_table');
mysqli_execute($tu);
$num_rows = mysqli_num_rows($tu);
echo $num_rows.' rows\n';
mysql has been deprecated. Please use mysqli.
Using MySQLi bind_param to get your result:
$someuser = 'Dave';
$DBH = mysqli_connect('localhost','user','pass','database');
$query = mysqli_prepare($DBH,'SELECT * FROM visitor_table WHERE user = ?');
mysqli_bind_param($query,'s',$someuser);
mysqli_execute($query);
mysqli_bind_result($id,$user,$tabCol1,$tabCol2);
while(mysqli_fetch_result){
$row = $row +1;
echo $user.': was found in the record with ID of: '.$id;
}
echo 'total records found:'.$row;
That's one way of doing it as I'm not completely 100% sure about using a mysqli_num_row() with the query above.