How to get count using prepared statment in PHP? - php

$con = mysqli_connect("localhost","root","","uploads");
if($con)
{
$sql = "SELECT COUNT(id) FROM products";
$obj = mysqli_query($con,$sql);
if(is_object($obj))
{
$rows = mysqli_fetch_row($obj);
$totalrows = $rows[0];
enter code here
}else{
echo "not object";
}
}else
{
echo "db issue";
}
This code is perfectly fine but i want to perform same operation using prepared statment.i have tried but could't get the same result using prepared statment. what i have to do?

Check out the following solutions
//db configuration
$server = 'localhost';
$dataBase = 'uploads';
$UserName = 'root';
$Password = '';
PHP MySQLi Prepared Statement
$con = mysqli_connect($server, $userName, $password, $dataBase);
$sql = "SELECT COUNT(id) FROM products";
$stmt = mysqli_prepare($con, $sql);
if(mysqli_stmt_execute($stmt)) {
mysqli_stmt_bind_result($stmt, $totalRows);
mysqli_stmt_fetch($stmt);
echo $totalRows;
}
PHP MySQLi Object-oriented
$con = new mysqli($server, $userName, $password, $dataBase);
$stmt = $con->query("SELECT COUNT(id) FROM products");
if ($stmt->num_rows > 0) {
while($row = $stmt->fetch_row()) {
$totalRows = $row[0];
echo 'Total number of rows is '.$totalRows;
}
}
$stmt->close();
PHP MySQLi with Object-oriented Prepared Statement
$con = new mysqli($server, $userName, $password, $dataBase);
$stmt = $con->prepare("SELECT COUNT(id) FROM products");
$stmt->execute();
$stmt->bind_result($totalRows);
$stmt->fetch();
echo 'Total number of rows is '.$totalRows;
$stmt->close();
PHP PDO with Prepared Statement
try {
$con = new PDO("mysql:host=$server;dbname=$dataBase;", $userName, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->prepare("SELECT COUNT(id) FROM products");
$stmt->execute();
$totalRows = $stmt->fetchColumn();
echo 'Total number of rows is '.$totalRows;
} catch(PDOException $e){
echo $e->getMessage();
die();
}

Related

Mysqli_num_row not generating the database row correctly

I am trying to get the row of my email in my database and I use the query so I can validate the email in my database and I used the code
if (isset($_POST['submit'])) {
$num = 1;
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'user_managment';
$connection = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
$query = mysqli_query($connection, "SELECT count(id) FROM users WHERE email = 'user#gmail.com'");
$result = mysqli_num_rows($query) == $num;
if ($result){
echo 'Yes';
}else{
echo 'No';
}
}
my database is here and I only have an email(alex#gmail.com)
but I do the notice these still echo out 'yes' whenever I insert email that ain't in my DB
That's because you do COUNT(*), this will always result in a single record.
A better solution would be:
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("SELECT email FROM users WHERE email=?");
$stmt->bind_param("s", $email);
$result = $stmt->execute();
if ($result->num_rows == 1) {
echo "Yes";
} else {
echo "No";
}
$stmt->close();
$conn->close();

Mysql get count with php prepared

I want get count rows in my table. How can I do it?
<?php
require_once "config.php";
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("SELECT COUNT(*) FROM `books`");
$stmt->execute();
$result = $stmt->get_result();
?>
Try this :
$query = "SELECT COUNT(*) FROM books";
$stmt = $conn->prepare($query);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($Count);
$stmt->fetch();
echo "Count: $Count";

Can't select data with PDO

I want to select data (at all) with PDO (always used mysqli) from an external database. It connects, and the query works on the server directly with mysql. With php, it doesn't. Here's my code:
<?php
$hostname = 'localhost';
$username = 'user';
$password = 'pass';
function testdb_connect ($hostname, $username, $password){
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
return $dbh;
}
try {
$dbh = testdb_connect ($hostname, $username, $password);
echo 'Connected to database';
} catch(PDOException $e) {
echo $e->getMessage();
}
$sql= "select * from table limit 10;";
echo "<br/>";
echo $sql;
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetchObject();
echo $row->id;
It shows "connected to database", and the "echo $sql" part, but doesn't display any information.
Your first part of the question have been solved.
now this
I now want to print the 10 rows instead of just the first one. How do
I do it?
The are many ways you can do that, but you need to loop through your results and display the desired Rows
Option 1
$sql = $dbh->query("SELECT * from table limit 10")->fetchall(PDO::FETCH_ASSOC);
foreach($sql as $row){
// print_r($row); // see them all
echo $row['desiredRow']; //print them one by one
}
Option 2
$sql = $dbh->query("SELECT * from table limit 10");
while($row=$sql->fetch()){
// print_r($row);
echo $row['desiredRow'];
}
Option 3
<?php
$sql = "SELECT * from table limit 10";
$stmt = $dbh->prepare($sql);
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0){//check results
foreach($results as $row){
print_r($row);
}
}else{
echo "no results found";
}
?>

How do I reconnect my web pages on my website after updating to PHP 7 with a MySQL database 5.0.0?<?

I added the i updates to communicate with the database & now the page links don't work.
<?php
// Connect to database
$link=mysqli_connect('localhost', 'xxxxx', 'xxxxx');
mysqli_select_db($link, 'waddellc_PHRDB');
$sql = "SELECT * FROM quotes ORDER BY id";
$result = mysqli_query($link, $sql) or die(mysql_error());
$tenant_quotes = array();
$owner_quotes = array();
while($row = mysqli_fetch_array($result)) {
This should do the work, using PDO :
$servername = "localhost";
$username = "username";
$password = "password123";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=databaseName", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(!is_null($conn)){
$stmt = $conn->prepare("SELECT * FROM quotes ORDER BY id");
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
}
I also think you need to update your database, it's quite old now.

select an attribute in mysql, php

I just start to learn about phpMyAdmin and mysql. here's a question: I want to select something in my "student" table and it echo the result. but as I checked it returns 0 row for the search. but I have it in my database.
here is my code:
$conn = new mysqli($servername, $username, $password, $dbname);
$params="#name varchar(30)";
$paramslist="#name='$name%";
$sql = "SELECT name,address,city,birthday FROM student WHERE NAME=#NAME";
$dbsql = "EXEC sp_executesql
N'$sql',
N'$params',
$paramslist";
$result = $conn->query($sql);
ECHO $result->num_rows;
I don't know what is the problem. thank you for helping.
$sql = "SELECT name,address,city,birthday FROM student WHERE name=".$name;
$result = $conn->query($sql);
echo $result->num_rows();
this is what works for me with prepared statement
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name='Veshraj Joshi';
$stmt = $conn->prepare("SELECT name,address,city,birthday FROM student WHERE NAME=?");
/* bind parameters for markers */
$stmt->bind_param("s", $name);
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
/* now you can fetch the results into an array */
while ($student = $result->fetch_assoc()) {
// use your $student array as you would with any other fetch
echo $student['address'].'<br>';
}
The following uses prepared statements. You should always use prepared statements when including user input to safeguard for SQL Injection attacks.
Every time fetch() executes, the results are bound to the variables specified by bind_result()
$conn = new mysqli($servername, $username, $password, $dbname);
$query = "SELECT name,address,city,birthday FROM student WHERE name=?";
$stmt = $conn->prepare($query);
$searchTerm = "%$name%";
$stmt->bind_param('s', $searchTerm);
$stmt->execute();
$stmt->bind_result($resultName, $resultAddress, $resultCity, $resultBirthday);
while($stmt->fetch())
{
echo $resultName . " " . $resultAddress . " " . $resultCity . "<br/>";
}

Categories