member count.. Array output numbers? - php

I am currently stuck..
When trying to fetch member count it returns as an array, which is not that easy to output when It's a number.. here is the code
Member.php
public function __construct() {
$this->_pdo = DB::connect();
}
public function count() {
$this->_query = $this->_pdo->query("SELECT COUNT(*) FROM members");
if(!$this->_query->error()) {
print_r($this->_query);
}
return false;
}
DB.php
private function __construct() {
try {
$this->pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/dbname'), Config::get('mysql/username'), Config::get('mysql/password'));
} catch(PDOException $e) {
die($e->getMessage());
}
}
public static function connect() {
if(!isset(self::$_connect)) {
self::$_connect = new DB();
}
return self::$_connect;
}
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->pdo->prepare($sql)) {
$x = 1;
if(count($params)) {
foreach($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
How can I output this in the correct way?

You need to fetch the data.
$this->_query->fetchColumn();

Related

"Uncaught PDOException: SQLSTATE[HY000]" When Trying to Insert [PHP 8.0]

So my code was working perfectly fine, until I tried to insert to the database..
my DB.php (The problem seems to be here, I checked all the other files and nothing is causing any problems, the function I used was the Insert function and I got an error on line 37:
<?php
class DB
{
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_result,
$_count = 0;
private function __construct()
{
try {
$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db') . '', Config::get('mysql/username'), Config::get('mysql/password'));
} catch (PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance()
{
if (!isset(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array())
{
$this->_error = false;
if ($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if (count($params)) {
foreach ($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if ($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
public function action($action, $table, $where = array())
{
if (count($where) == 3) {
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if (in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if ($this->query($sql, array($value))) {
return $this;
}
}
}
return false;
}
public function get($table, $where)
{
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where)
{
return $this->action('DELETE *', $table, $where);
}
public function error()
{
return $this->_error;
}
public function count()
{
return $this->_count;
}
public function insert($table, $fields = array())
{
if (count($fields)) {
$keys = array_keys($fields);
$values = '';
$x = 1;
foreach($fields as $field){
$values .= "?";
if($x < count($fields)){
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO users (`" . implode('`,`', $keys) . "`) VALUES ({$values})";
echo $sql;
if(!$this->query($sql, $fields)->error()){ //where my error occurred
return true;
}
}
return false;
}
}
(The data's inserted to the table but that error seems crucial and I didn't find anything about it anywhere)
I watched a tutorial on YouTube and the problem occurred here- https://youtu.be/zvXgsouIzVg?t=5258
(The full error):
Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error in D:\xampp\htdocs\classes\DB.php:37 Stack trace: #0 D:\xampp\htdocs\classes\DB.php(37): PDOStatement->fetchAll(5) #1 D:\xampp\htdocs\classes\DB.php(93): DB->query('INSERT INTO use...', Array) #2 D:\xampp\htdocs\test.php(4): DB->insert('users', Array) #3 {main} thrown in D:\xampp\htdocs\classes\DB.php on line 37
Thanks in advance, that would help me a lot!

PHP How to insert into a table using a function correctly?

I'm learning from a tutorial online, but I can't seem to get my SQL statements to insert into the database. This is my first try at functions. I'm thinking it's the "back-tick" in my SQL statement here:
$sql = "INSERT INTO users (`" . implode('`, `', $keys) . "`) VALUES (".$values.")";`
Anyway here's my code db.php:
class DB
{
private static $_instance = null;
private
$_pdo,
$_query,
$_error = false,
$_results,
$_count = 0;
private function __construct()
{
try
{
$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname='.Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
echo 'Connected<br>';
}
catch(PDOException $e)
{
die($e->getMessage());
}
}
public static function getInstance()
{
if(!isset(self::$_instance))
{
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array())
{
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql))
{
$r = 1;
if (count($params))
{
foreach($params as $param)
{
$this->_query->bindValue($r, $param);
$r++;
}
}
if($this->_query->execute())
{
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
echo 'success<br>';
}
else
{
$this->_error = true;
}
}
return $this;
}
public function action($action, $table, $where = array())
{
if(count($where) === 3)
{
$operators = array('=', '>', '<', '<=', '>=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators))
{
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, array($value))->error())
{
return $this;
}
}
}
return false;
}
public function get($table, $where)
{
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where)
{
return $this->action('DELETE *', $table, $where);
}
public function insert($table, $fields = array())
{
if(count($fields))
{
$keys = array_keys($fields);
$values = '';
$r = 1;
foreach($fields as $field)
{
$values .= '?';
if($r < count($fields))
{
$values .= ', ';
}
$r++;
}
//die($values);
$sql = "INSERT INTO users (`" . implode('`, `', $keys) . "`) VALUES (".$values.")";
echo $sql;
if(!$this->query($sql, $fields)->error())
{
return true;
}
}
return false;
}
public function error()
{
return $this->_error;
}
public function count()
{
return $this->_count;
}
public function results()
{
return $this->_results;
}
public function first()
{
return $this->results()[0];
}
}
and here's my index.php:
$user = DB::getInstance()->insert('users', array(
'username' => 'Dale',
'password' => 'password',
'salt' => 'salt'
));
if($user){ echo 'true';}
I've tried removing the "back-ticks" (that's what the guy in the tutorial called them, (`), but that didn't work. I'm trying to get the index.php to insert the data into my database. Any help would be appreciated.

How to convert a simple set of php instructions to a PDO function

I would like to create a PDO function where I can pass a variable to it and get the result shown below.
The variable I would like to pass is called $range.
I would like to call the function by:
$range=$row["part_number"];
function get_range($range);
Then to get the result show below:
<?php
$range = "gmb3-30";
include ("order/connection.php");
// --------------------- Connect to the table-------------------------
$stmt = $pd->prepare('SELECT * FROM mytable WHERE part_number = :part_number');
$stmt->execute(array(
':part_number' => $range
));
$row = $stmt->fetch(PDO::FETCH_BOTH);
echo " <select name=select>";
$c = $row["price_each1"]; // price for single item
for ($i = 1; $i <= 8; $i++)
{
$b = $row["price_each" . $i];
if ($b != 0.00)
{
$d = (($c - $b) / $c) * 100;
$complete = $row[("price_break" . $i) ] . " ," . round($d) . "%";
echo "<option> ";
echo $complete . "</option>";
}
}
echo “ < / select > ”;
?>
Create a class like this and include it:
<?php
class Database{
// Define configuration
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
// Declare a new variables at the top of your class for the Database Handler and any errors.
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname.';charset=utf8;';
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function simpleSingle(){
$this->execute();
//$this->stmt->fetch(PDO::FETCH_ASSOC);
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
public function beginTransaction(){
return $this->dbh->beginTransaction();
}
public function endTransaction(){
return $this->dbh->commit();
}
public function cancelTransaction(){
return $this->dbh->rollBack();
}
public function debugDumpParams(){
return $this->stmt->debugDumpParams();
}
}
Then replace your code by this one:
function get_range($range) {
$database = null;
$database = new Database();
$database->query("SELECT * FROM mytable WHERE part_number = :part_number;");
$database->bind(':part_number', $range);
$row = $database->resulset();
if (!$row) {
// Do whatever needs to be done when you get no results
die();
} else {
echo " <select name=select>";
$i = 0;
foreach ($row as $option) {
if ($i <= 8){
$b=$option["price_each"];
if ($b !=0.00)
{
$d=(($c-$b)/$c)*100;
$complete=$option[("price_break"]. " ," .round($d)."%";
echo "<option> ";
echo $complete ."</option>";
}
$i = $i + 1;
}
}
echo “</select>”;
}
}
And in the end, call the function:
$range=$row["part_number"];
function get_range($range);

Issue with MySQL query using PDO and OOP

I'm having a problem with my login script. I'm trying to make a method to make my mySQL query handling easier.
My code should return "OK!" to the page, but instead it returns "No user", which means that it counts 0 rows. I've tested the mySQL query on phpMyAdmin, and it works fine there.
My Code:
DB.php:
public function action($action, $table, $where = array()) {
if(count($where) === 3) {
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, array($value))->error()) {
return $this;
}
}
}
}
public function get($table, $where) {
return $this->action('SELECT *', $table, $where);
}
public function count() {
return $this->count;
}
Index.php:
$user = DB::getInstance()->get('digi_users.users', array('username', '=', 'chris'));
if(!$user->count()) {
echo 'No user';
} else {
echo 'OK!';
}
Any help is much appreciated!
UPDATE
I'm establishing a database connection in my DB Class (DB.php).
I actually have multiple databases, so I created a couple connections.
Code in DB Class:
private function __construct() {
/* Connect to DB 1 */
try {
$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db1'), Config::get('mysql/username'), Config::get('mysql/password'));
} catch(PDOException $e) {
die($e->getMessage());
}
/* Connect to DB 2 */
try {
$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db2'), Config::get('mysql/username'), Config::get('mysql/password'));
} catch(PDOException $e) {
die($e->getMessage());
}
/* Connect to DB 3 */
try {
$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db3'), Config::get('mysql/username'), Config::get('mysql/password'));
} catch(PDOException $e) {
die($e->getMessage());
}
/* Connect to DB 4 */
try {
$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db4'), Config::get('mysql/username'), Config::get('mysql/password'));
} catch(PDOException $e) {
die($e->getMessage());
}
/* Connect to DB 5 */
try {
$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db5'), Config::get('mysql/username'), Config::get('mysql/password'));
} catch(PDOException $e) {
die($e->getMessage());
}
/* Connect to DB 6 */
try {
$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db6'), Config::get('mysql/username'), Config::get('mysql/password'));
} catch(PDOException $e) {
die($e->getMessage());
}
}
The getInstance() function creates a new DB instance.
Code from DB Class:
public static function getInstance() {
if(!isset(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
Query() method from DB Class:
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if(count($params)) {
foreach($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
check your method :
public function count() {
return $this->count;
}
versus:
public function query($sql, $params = array()) {
...
$this->_count = $this->_query->rowCount();
...
}
I guess you should change count() to:
public function count() {
return $this->_count;
}
From your query method in your class you have this line:
$this->_count = $this->_query->rowCount();
so when you want to read the count value you can call it with
print $user->_count;
or have you made a getter method to return the _count value? if so you need to show that to us. Also helpful to yourself if you do a var_dump of the $user object to see what values and functions it holds.

How to query all entries from the database by id?

I was following this tutorial on Udemy about building login form. Everything went well.
Now I'm trying to reuse the code. The problem I'm having is when I'm trying to query all entries from a database in order to get a total number of websites. Could you please advise?
Here is my count function (this is where I'm having issues in obtaining a total number of entries to the database for pagination):
function get_all_websites(){
$all = array();
$db = DB::getInstance();
$all = $db->query("SELECT * FROM website");
if(!$all->count()){
echo 'No Websites available. Please check back later.';
} else {
foreach($all->results() as $all){
$all->id = $all;
}
}
return $all;
}
function get_websites_count(){
return count(get_all_websites());
}
if I use this I get all ID's listed.
function get_all_websites(){
$all = array();
$db = DB::getInstance();
$all = $db->query("SELECT * FROM website");
if(!$all->count()){
echo 'No Websites available. Please check back later.';
} else {
foreach($all->results() as $all){
echo $all->id;
}
}
}
Database class.
class DB{
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_count = 0;
private function __construct(){
try {
$this->_pdo = new PDO('mysql:host=' .
Config::get('mysql/host') . ';dbname=' .
Config::get('mysql/db'),
Config::get('mysql/username'),
Config::get('mysql/password'));
} catch(PDOException $e){
die($e -> getMessage());
}
}
public static function getInstance(){
if(!isset(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array()){
$this->_error = false;
// Check if query has been prepared properly
if($this->_query = $this->_pdo->prepare($sql)){
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
// If the query has been prepared successfuly, store the result
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
public function action($action, $table, $where = array()){
if(count($where) === 3){
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)){
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, array($value))->error()){
return $this;
}
}
}
return false;
}
// QUERYING DATA FROM DATABASE
public function get($table, $where){
return $this->action('SELECT *', $table, $where);
}
// DELETING DATA FROM DATABASE
public function delete($table, $where){
return $this->action('DELETE', $table, $where);
}
// INSERTING DATA INTO DATABASE
public function insert($table, $fields = array()){
$keys = array_keys($fields);
$values = '';
$x = 1;
foreach($fields as $field){
$values .= "?";
if($x < count($fields)){
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES({$values})";
if(!$this->query($sql, $fields)->error()){
return true;
}
return false;
}
public function results(){
return $this->_results;
}
public function update($table, $id, $fields){
$set = '';
$x = 1;
foreach($fields as $name => $value){
$set .= "{$name} = ?";
if($x < count($fields)){
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()){
return true;
}
return false;
}
public function first(){
return $this->results()[0];
}
public function error(){
return $this->_error;
}
public function count(){
return $this->_count;
}
}
This part doesn't seem right:
} else {
foreach($all->results() as $all){
$all->id = $all;
}
}
return $all;
but I'm not exactly sure what you want.
We could append each id to an array called $allWebsiteIds:
} else {
foreach($all->results() as $all){
$allWebsiteIds[] = $all->id;
}
}
return $allWebsiteIds;
That might give you what you want.
SQL provides built-in support for counting rows in a table.
SELECT COUNT(*) FROM ...
This is highly optimizable and avoids loading every row into PHP's memory.
Additionally, pay close attention to the construct of your loops; specifically what it means to say:
foreach($foo as $foo)
As part of your study, you should be able to say why that expression is almost never the intended one.
There is a broader rule: Never mutate that which you are iterating over.
Why not use the select to count the rows?
SELECT COUNT(1) FROM website;

Categories