How to display the number of rows using the SQL query COUNT - php

When I run this query SELECT COUNT(ID) FROM blog_posts in PHPmyadmin it returns the number of rows in my database which is what I want but now I want this number to be displayed on my success.php page using the count method below.
Heres my code so far:
Database.class.php
<?php
include 'config/config.php'; // Inlude the config file, this is where the database login info is stored in an array
class database {
private $dbc; // Define a variable for the database connection, it's visabiliatly is set to 'private' so only this class can access it
function __construct($dbConnection){
// Running the __construct() magic function,
// I am passing through a variable into the contruct method which when the object is created will hold the login details from the $dsn array in config.php
$this->dbc = $dbConnection; // This is saying that the variable $dbc now has the same value as $dbConnection ($dsn array)
$this->dbc = mysqli_connect($this->dbc['host'], $this->dbc['username'], $this->dbc['password'], $this->dbc['database']);
// ^ Running the mysqli_connect function to connect to the database.
if(mysqli_connect_errno()){ // If there is a problem connecting it will throw and error
die("Database connection failed" . mysqli_connect_error());
} else {
echo "allgood";
}
}
function insert($insertSQL){ // Creating an insert function and passing the $insertSQL variable into it
mysqli_query($this->dbc, $insertSQL); // Querying the database and running the query that is located in 'success.php'.
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $insertSQL" . $this->dbc->error);
}
}
function count($countSQL){ // This is the method used for counting
mysqli_query($this->dbc, $countSQL);
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $countSQL" . $this->dbc->error);
}
}
}
?>
Success.php
<?php
include 'classes/database.class.php';
include 'config/config.php';
echo '<h2>Success page</h2>';
$objdb = new database($dsn);
$insertSQL = "INSERT INTO blog_posts VALUES(NULL, 'Test', 'THis is a message')";
$objdb->insert($insertSQL);
$countSQL = "SELECT COUNT(ID) FROM blog_posts";
$objdb->count($countSQL); // Executes the query, now how do I display the result? I have tried 'echo'ing this but it doesn't seem to work
?>

Actually its much better to add an alias in your query:
$countSQL = "SELECT COUNT(ID) as total FROM blog_posts";
$result = $objdb->count($countSQL);
echo $result['total'];
Then, on your methods:
function count($countSQL){ // This is the method used for counting
$query = mysqli_query($this->dbc, $countSQL);
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $countSQL" . $this->dbc->error);
}
$result = $query->fetch_assoc();
return $result;
}
Additional Info:
It might be good also on your other methods to put a return value. So that you'll know that it worked properly.
Example:
function insert($insertSQL){ // Creating an insert function and passing the $insertSQL variable into it
$query = mysqli_query($this->dbc, $insertSQL); // Querying the database and running the query that is located in 'success.php'.
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $insertSQL" . $this->dbc->error);
}
return $this->dbc->affected_rows;
}
So that here:
$insertSQL = "INSERT INTO blog_posts VALUES(NULL, 'Test', 'THis is a message')";
$insert = $objdb->insert($insertSQL); // so that its easy to test if it indeed inserted
if($insert > 0) {
// hooray! inserted!
}

Related

how to make a query with database as a variable

I have two databases - lorem and nts.lorem - and need to operate with both of them
$user = 'root';
$pass = '';
$db1 = new PDO('mysql:host=localhost; dbname=nts.lorem', $user, $pass);
$db2 = new PDO('mysql:host=localhost; dbname=lorem', $user, $pass);
everything works fine until db is a variable in an ajax request - for example:
js
var db;
if(something is true){db = 'db1';};
else{db = 'db2';}
//... ajax post code
php
function something($db){
global $db1, $db2;
// how to say the next line
$sq = "select id from " . $db . ".tableName order by title asc";
// error - table db1.tableName doesn't exist
}
any help?
Choose connection according to $db value:
function something($db){
global $db1, $db2;
$sq = "select id from tableName order by title asc";
if ($db === 'db1') {
$db1->execute($sq);
} else {
$db2->execute($sq);
}
// rest of the code
}
Add the line that executes the query to your code sample. Without it, it's hard to be sure what's wrong, but I can guess: you don't need the name of the database in the query text, you need to execute the query with the proper database connection, based on the parmeter received from the client.
Something like:
function something($db){
global $db1, $db2;
$sq = "select id from tableName order by title asc";
$stmt = $db === 'db1' ? $db1->query($sq) : $db2->query($sq);
$result = $stmt->fetch();
}
Comment: this assumes you have a table called tableName in both databases.

Function fetch() when I want to check [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
I receive this error:
Fatal error: Call to a member function fetch() on boolean in
C:\xampp\htdocs\repo\generator\model\database.php on line 34
When I run this code:
class database
{
private $user = 'root';
private $pass = '';
public $pdo;
public function connect() {
try {
$this->pdo = new PDO('mysql:host=localhost; dbname=generatordatabase', $this->user, $this->pass);
echo 'Połączenie nawiązane!';
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone: ' . $e->getMessage();
}
}
public function createTable() {
$q = $this->pdo -> query('SELECT * FROM article');
while($row = $q->fetch()) {
echo $row['id'].' ';
}
$q->closeCursor();
}
}
?>
As per the PHP manual for PDO::query
PDO::query() returns a PDOStatement object, or FALSE on failure.
It looks like your query is failing (on line 33) and thus returning a BOOLEAN (false), likely because at that point in execution, PDO has not connected to a database that contains a table called article. In the connect() method I see that it tries to connect to a db called 'generatordatabase'; ensure this connection is being made prior to calling createTable(), otherwise ensure that it contains a table called 'article'.
I would recommend adding some more code examples, for instance the code that calls this class/method before the error is triggered.
Some error handling will help you avoid issues like this:
$q = $this->pdo->query('SELECT * FROM article');
//error case
if(!$q)
{
die("Execute query error, because: ". print_r($this->pdo->errorInfo(),true) );
}
//success case
else{
//continue flow
}
I'm not sure wheatear this is exactly the error I struggled with, but my error was due to my $con variable, I used a single $con for 2 SQL statements, for example:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con->prepare($sql1);
if ($stm1->execute()) {
I should have done:
$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";
$stm = $con->prepare($sql);
$stm->execute();
and
$con1 = new mysqli($host,$username,$password,$database);
$sql1 = "INSERT INTO posts
VALUES('$email','$body')";
$stm1 = $con1->prepare($sql1);
$stm1->execute()

PDO not working if I re-run a function inside itself

I'm trying to create a system, where my website generates an unique code (current date + 5 random characters) and that code is transferred to a table in my database.
Before function generateNumber() can insert the unique code into the database, it has to check if the code already exist in the database.
If the code doesn't exist, my function works flawlessly. But the problem is when the code can already be found on the database, my website just doesn't do anything (it should just re-run the function).
function generateNumber()
{
global $conn;
$rand = strtoupper(substr(uniqid(sha1(time())),0,5));
$result = date("Ydm") . $rand;
$SQL = $conn->query("SELECT code FROM test WHERE code='$result'");
$c = $SQL->fetch(PDO::FETCH_ASSOC);
if ($c['code'] > 0) { // test if $result is already in the database
generateNumber();
} else {
$sql2 = "INSERT INTO test (code) VALUES (?)";
$stmt2 = $conn->prepare($sql2);
$stmt2->execute([$result]);
return $result;
}
}
try {
$conn = new PDO("sqlite:db"/*, $username, $password*/);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo generateNumber();
}
catch(PDOException $e) {
echo "Error:" . $e->getMessage();
}
$conn = null;
?>
There are no error messages in the console, but I suspect the problem is this part of the code:
if ($c['code'] > 0) { // test if $result is already in the database
generateNumber();
}
Any idea how I can write this function in a better way?
Solution :
if ($c['code'] > 0) { // test if $result is already in the database
// if the code exists in db the function return nothing
// because you are missing a return :
return generateNumber();
}

cant catch assoc array, confirmed that there is results there but wont select and show

This could be a simple syntax error but I've tried every I know how. I have a database class for selecting data
<?php
/* this script is for creating a class to connect to the database */
include "includes/config.php";
class database {
protected static $connection; // variable to hold the mysqli connection
protected function connect(){
if (!isset(self::$connection)){ // if the connection variable is not set
self::$connection = new mysqli(SERVER_NAME, USERNAME, PASSWORD, DB_NAME); // set the connection
}
if (self::$connection === false){ //in case connection failed return false
return false;
}
else {
return self::$connection; // returns the connection
}
}
protected function query($query){ // public function to take a sql query
$connection = $this->connect(); // calls the connect function to create a connection to the database
$result = $connection->query($query); // puts the query into the result variable
return $result; //returns the result
}
public function select($query){
$rows = array();
$result = $this->query($query);
if($result === false){
return false;
}
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
return $rows;
}
public function error(){
$connection = $this->connect();
return $connection->error;
}
}
?>
I have instantiated this in index.php. I made a query and passed it to the select method then ran an if statement to say that if the size of the result is greater than or equal to 1 then echo query successfully. Here's where I keep screwing up. I'm trying to just print out the value of first_name but no matter what way I try it won't print. is this a 2d associative array?
<?php
include 'view/header.php';
include 'includes/connect.php';
$db = new database();
$sql = "SELECT `first_name`, `last_name` FROM `pratts_db`
WHERE `first_name` = `clive`;";
$result = $db->select($sql);
if (sizeof($result) >= 1){
echo "query successful";
echo "<p>{$result[`first_name`]}</p>";
}
include 'view/footer.php';
?>
I've tried it with different quotation marks, tried selecting 0 position then the first_name and it doesn't work. what am I missing?
$result is a 2-dimensional array. Each element of the array is a row of results, and the columns are elements of those associative arrays.
So you need to loop over the results:
foreach ($result as $row) {
echo "<p>{$row['first_name'}</p>";
}
If you only need the result from the first row (e.g. if you know the query can't match more than one row), you can index it instead of looping:
echo "<p>{$result[0]['first_name']}</p>";
You also have the wrong kind of quotes around first_name in
$result[`first_name`]
They should be single or double quotes, not backticks. And in the SQL, you should have single or double quotes around clive, unless that's a column name. See When to use single quotes, double quotes, and back ticks in MySQL

PHP mysql return parameter when query result == true

In php I call a procedure in mysql. Now I want to check if a query result == true then set return variable in my php file in true or false if query failed. How can I do that?
This is my php code:
public function DeleteSingleAccount($accountId)
{
$Config = new Config();
$mysqli = $Config->OpenConnection();
mysqli_query($mysqli, "CALL DeleteSingleAccount($accountId)") or die("Query fail: ". mysqli_error());
}
This is my query in mysql for now:
DELETE
FROM table
WHERE accountId = par_AccountId
This code runs correct but I want to set an return parameter when query is true or false.
public function DeleteSingleAccount($accountId)
{
$Config = new Config();
$mysqli = $Config->OpenConnection();
return !! mysqli_query($mysqli, "CALL DeleteSingleAccount(" . intval($accountId) . ")");
}
I added intval() to avoid SQL injection (not needed if you're sure $accountId is always an integer, never null, empty string, user input, etc.)
Think your looking for something like this:
public function DeleteSingleAccount($accountId) {
$Config = new Config();
$mysqli = $Config->OpenConnection();
$result = mysqli_query($mysqli, "CALL DeleteSingleAccount($accountId)") or die("Query fail: ". mysqli_error());
//^Assignment of the query to a variable
if($result && mysqli_num_rows($result) > 0) {
//^Check if query is successfull ^ Check if query has 1 or more rows in it! (You can delete this check if you don't care about how many row's the result has)
echo "The query is successful and have 1 or more rows in it!";
} else {
echo "The query failed or have 0 rows in it!";
}
}

Categories