Using one of the tutorials I managed to create a working database retrieval using PHP, JSON and jQuery
Now my question is, if I have multiple query statements that I want to execute what is the best solution?
I have tried opening a second connection in different functions and sending the information as an array in array but that does not work.
database.php:
<?php
function getDbConnection() {
$db = new PDO(DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER, DB_USER);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
function home_ratings() {
$db = getDbConnection();
$stmt1 = $db->prepare("select * from table1");
$isOk1 = $stmt1->execute();
$results_home = array();
if ($isOk1)
{
$results_home = $stmt1->fetchAll();
}
else
{
trigger_error('Error executing statement.', E_USER_ERROR);
}
$db = null;
return $results_home;
}
?>
get.php:
<?php
require('constant.php');
require('database.php');
$home = home_ratings();
//$top_rest = top_ratings();
//$newr = new_ratings();
//echo json_encode($home);
echo json_encode(array('home' => $home));
?>
info.js:
$( document ).ready(function() {
$.get( "php/get.php")
.done(function(data) {
var results = jQuery.parseJSON(data);
$.each(results, function(i, value) {
//do what i need to do here
})
});
});
You only need one database connection object if you're connecting to the same database in the same method. Instead of having a function for getDbConnection() instead make the $db variable global and use it within functions (you may need to put a line global $db; in the function to ensure that it can access the global variable).
Example of how your database.php file could look:
<?php
$db = new PDO(DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER, DB_USER);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function home_ratings() {
global $db; // $db scope of global
$stmt1 = $db->prepare("select * from table1");
$isOk1 = $stmt1->execute();
$results_home = array();
if ($isOk1)
{
$results_home = $stmt1->fetchAll();
}
else
{
trigger_error('Error executing statement.', E_USER_ERROR);
}
return $results_home;
}
?>
Related
I am new to the idea of oop php and i am trying to write an irc php.
What I'm trying to do:
I am trying to query my database, get results from my database and put it into an array inside my program.
I tried making a new function to carry out the task and called it in the __construct function.
I have shortened the code but it pretty much looks like this:
Any thoughts and ideas are much appreciated.
class IRCBot
{
public $array = array();
public $servername = "localhost";
public $username = "root";
public $password = "usbw";
public $dbname = "bot";
function __construct()
{
//create new instance of mysql connection
$conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$this->database_fetch();
}
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($query);
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row();
}
}
function main()
{
print_r($array);
}
}
$bot = new IRCBot();
Changes
1) Change if ($mysqli->connect_errno) to if ($conn->connect_errno)
2) Change $array[] = $row(); to $array[] = $row;
3) Add return $array; in function database_fetch()
4) Call database_fetch() function inside main() function instead of constructor.
5) Add $this->conn in mysqli_query() (Thanks #devpro for pointing out.)
Updated Code
<?php
class IRCBot
{
public $array = array();
public $servername = "localhost";
public $username = "root";
public $password = "usbw";
public $dbname = "bot";
public $conn;
function __construct()
{
//create new instance of mysql connection
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_errno)
{
echo "Failed to connect to MySQL: (" . $this->conn->connect_errno . ") " . $this->conn->connect_error;
}
}
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($this->conn,$query);
while($row = mysqli_fetch_assoc($result)){
$array[] = $row;
}
return $array;
}
function main()
{
$data = $this->database_fetch();
print_r($data);
}
}
Quick Start
Object Oriented Programming in PHP
Classes and Objects
Principles Of Object Oriented Programming in PHP
First of all you need to fix error from your constructor, you can modify as:
function __construct()
{
//create new instance of mysql connection
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_errno)
{
echo "Failed to connect to MySQL: (" . $this->conn->connect_errno . ") " . $this->conn->connect_error;
}
echo $this->conn->host_info . "\n";
}
Here, you need to replace $mysqli with $conn because your link identifier is $conn not $mysqli
No need to call database_fetch() here.
You need to use $conn as a property.
Now you need to modify database_fetch() method as:
function database_fetch()
{
$query = "SELECT word FROM timeoutwords";
$result = mysqli_query($this->conn,$query);
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
return $array;
}
Here, you need to pass add first param in mysqli_query() which should be link identifier / database connection.
Second, you need to use return for getting result from this function.
In last, you need to modify your main() method as:
function main()
{
$data = $this->database_fetch();
print_r($data);
}
Here, you need to call database_fetch() method here and than print the data where you need.
This is my code in config.php file:
<?php
$db_username = 'name';
$db_password = 'my password';
$db_name = 'my db';
$db_host = 'localhost';
$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
if ($mysqli->connect_error) {
throw new Exception("Error in Database Connection!");
}
?>
Now I have separate function.php with class commonFunctions
<?php
require_once '../config/config.php';
class commonFunctions {
function doLogin(){
global $mysqli;
$result = $mysqli->query("SELECT * FROM table WHERE itemcolor = 'red'") ;
$row_cnt = $result->num_rows;
return $row_cnt;
}
}
$common=new commonFunctions();
?>
Here I am using global $mysqli; to access $mysqli from config, which may not be a appropriate way to program and using global $mysqli; in every function to access $mysqli looks so bad.
Can you guys pls suggest better and clean way.
Thanks
It depends what programming paradigm you're comfortable with. Personally I like my PHP to be Object Orientated (OO), so i'd put the mysql in a new class called DB or something and then when I want to run the query i'd do $db->query('blabla').
class DB {
private $db;
function __construct() {
$dbConfig = Main::app()->config['db'];
$this->db = new \mysqli($dbConfig['host'], $dbConfig['user'], $dbConfig['pass'], $dbConfig['db']);
}
public function query($query, $where = false) {
if (!empty($where)) {
if (strpos(strtolower($where), 'where') > 0)
$query .= ' ' . $where;
else
$query .= ' WHERE ' . $where;
}
$result = $this->db->query($query);
if (!isset($result) || $result === false) {
dd([$query, $this->db->error, $where]);
}
/* will return true on INSERT / UPDATE queries */
if ($result !== true)
return $result->fetch_all(MYSQL_ASSOC);
}
}
Maybe you might just want to create a function in commonFunctions that handled all queries?
function query($query) {
global $mysqli;
return $mysqli->query($query);;
}
When I'm using mysqli without class it's going ok:
index.php
require_once(dirname(__FILE__) . '/config.php');
$mysqli = new mysqli($hostname, $username, $password, $dbname);
$queryText = "SELECT * FROM User";
if($query = $mysqli->query($queryText)) {
$results = $query->fetch_array();
echo $results['userId'];
} else {
echo "Error ";
echo $mysqli->errno . " " . $this->mysqli->error;
}
?>
But when I start using mysqli with class something goes wrong. connectDB doesn't give any error, so i get connected to DB. But then when trying do any query it give me "No database selected error"
Result of index.php is: Error 1046 No database selected
index.php
<?php
require_once(dirname(__FILE__) . '/banana.php');
$banana = new Banana(1);
if ($banana->connectDB()) {
$banana->doQuery();
}
?>
banana.php
<?php
require_once(dirname(__FILE__) . '/config.php');
class Banana {
private $mysqli, $userId, $query;
function __construct($userId) {
$this->userId = $userId;
}
function __destruct() {
$this->mysqli->close();
}
public function connectDB() { // Подключение к БД
$this->mysqli = new mysqli($hostname, $username, $password, $dbname);
if ($this->mysqli->connect_errno) {
echo "Error (" . $this->mysqli->connect_errno . ") " . $this->mysqli->connect_error;
return false;
}
return true;
}
public function doQuery() {
$queryText = "SELECT * FROM User";
if($this->query = $this->mysqli->query($queryText)) {
$results = $query->fetch_array();
echo $results['userId'];
} else {
echo "Error ";
echo $this->mysqli->errno . " " . $this->mysqli->error;
}
}
?>
So it's very frustrating. I'm about 2 weeks in php, but can't find answer for couple days. I guess the answer is obvious but I can't see it.
Thank you for your time and patience.
One of the first problems you will encounter when you run your script is here:
public function connectDB() { // Подключение к БД
$this->mysqli = new mysqli($hostname, $username, $password, $dbname);
Note that all 4 variables you are using in your function call ($hostname, etc.) are undefined in the scope of the method.
There are several ways you can solve this:
Pass the variables as parameters to the method:public function connectDB($hostname, ...
Pass the necessary variable to your class constructor and set configuration properties in your class that you can use later on;
Use constants instead of variables;
Declare your variables global.
I would recommend one of the first 2 and definitely not the last one.
You can read more in the php manual about variable scope.
It looks like you are a copy'n'paste victim. In doQuery() change:
if($this->query = $this->mysqli->query($queryText)) {
$results = $query->fetch_array();
To:
if($this->query = $this->mysqli->query($queryText)) {
$results = $this->query->fetch_array();
I've bought a domain-hosting from a local company. Their customer service is pretty horrible.
My code for connecting to the database seems ok but still its not working. Here my code:
function __construct(){
if(!#mysql_ping()){
$this->db_connect();
}
$sql = "SELECT value FROM settings WHERE field = 'auto_logout'";
$res = mysql_fetch_array($this->execute_single_query($sql));
$this->LOGIN_DURATION = $res['value'];
}
private function db_connect(){
// Mysql connect
$link = #mysql_connect('localhost', 'created_who_has_all_prev', 'pass_note_my_cpanel_and_mysql_has_same_pass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully<br/>';
// Mysql select db select --->
$db_selected = mysql_select_db($this->DB, $link);
if (!$db_selected) {
die ('Can\'t use specified Database : ' . mysql_error());
}
//echo "<br/>Database Selected<br/>";
return $link;
}
And this is the snapshot:
Your main problem is that the link that you create isn't accessible. So, PHP tries to connect with defaults (apparently in your setup it means the user is root) and since it has no password, the connection fails which is the cause of most of your warning messages.
The last warning is a consequence of the others.
To fix this problem - as you haven't provided details of the actual parts that are executing the query - here is how to re-write your code so it works:
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "(".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
$sql = "SELECT `value` FROM `settings` WHERE `field` = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s","auto_logout");
if (!$stmt->execute()) {
echo "(".$stmt->errno.") ".$stmt->error;
}
$res = $stmt->get_result();
$row = $res->fetch_assoc();
LOGIN_DURATION = $row['field'];
This is really sloppy code. I would use PDO as it is secure. Below is a class you can use but study how it works and why it works.
class Core {
public $dbh; // handle of the db connection
private static $instance;
private function __construct() {
$options = array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$this->dbh = new PDO("mysql:host=localhost;dbname=dealership", "root", "",$options);
}
public static function getInstance() {
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __clone() {}
private function __wakeup() {}
}
In your code call it like below:
require "/classes/pdo.class.php";
$db = Core::getInstance();
$stmt = "SELECT `lastname` FROM `employees` where id = 2";
$pep = $db->dbh->prepare($stmt);
$pep->execute();
foreach($pep->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo $row['lastname']. "\n";
}
Make sure you look into PDO, prepared statments, and singleton pattern to understand why it works.
I know I can close a PDO SQL connection setting the handler to NULL.
But if I don't do that, does PHP close the connection at the end of the script?
Fore example, can I use
$db = new PDO('sqlite:db.sqlite');
/* Code */
if ($cond1) { exit; }
/* More code */
if ($cond2) { exit; }
/* ... */
$db = NULL;
/* Code not related to the database */
... or should I use this:
$db = new PDO('sqlite:db.sqlite');
/* Code */
if ($cond1) {
$db = NULL;
exit;
}
/* More code */
if ($cond2) {
$db = NULL;
exit;
}
/* ... */
$db = NULL;
/* Code not related to the database */
According to the docs:
The connection remains active for the lifetime of that PDO object. To
close the connection, you need to destroy the object by ensuring that
all remaining references to it are deleted--you do this by assigning
NULL to the variable that holds the object. If you don't do this
explicitly, PHP will automatically close the connection when your
script ends.
EXAMPLE.
This is your dbc class
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getAllData($qty) {
//prepared query to prevent SQL injections
$query = "select * from TABLE where qty = ?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $qty, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
$getList = $db->getAllData(25);
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
Your connection will be closed as soon as the results are returned
According to the docs When you call exit:
Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit is called.
This means your PDO connection will be closed. It's always good practice to close it yourself though.