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();
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.
I'm trying to build a basic API with PHP and mysql and depending on the url path, different database tables are used and therefore the connection needs to be made. But I keep getting this error:
Fatal error: Call to a member function prepare() on a non-object
in....line 6
dashboard.class.php:
class dashboard {
public function getData($conn) {
// Get latest status
$stmt = $conn->prepare("SELECT status FROM status_archive ORDER BY datetime DESC LIMIT 1 ");
$stmt->execute(); //line 6
$stmt->bind_result($status);
$stmt->fetch();
($status == '1' ? $status = 'up' : $status = 'down');
$stmt->close();
return $status;
}
}
Function that creates the database connection:
function db_connection($type) {
$db = $type.'_db';
syslog(LOG_INFO, 'DB: '.$db);
// Check to see if a development or production server is being used
if (strpos(getenv('SERVER_SOFTWARE'), 'Development') === false) {
$conn = mysqli_connect(null,
getenv('PRODUCTION_DB_USERNAME'),
getenv('PRODUCTION_DB_PASSWORD'),
$db,
null,
getenv('PRODUCTION_CLOUD_SQL_INSTANCE'));
} else {
$conn = mysqli_connect(getenv('DEVELOPMENT_DB_HOST'),
getenv('DEVELOPMENT_DB_USERNAME'),
getenv('DEVELOPMENT_DB_PASSWORD'),
$db);
}
// Check if successful connection to database
if ($conn->connect_error) {
die("Could not connect to database: $conn->connect_error " .
"[$conn->connect_errno]");
}
return $conn;
}
This is the code at the end of the file that initiates everything:
$path_array = explode("/", parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));
$conn = db_connection($path_array[3]);
include 'classes/dashboard.class.php';
$dashboard = new dashboard;
$results = $dashboard->getData($conn);
echo json_encode($results, JSON_PRETTY_PRINT);
mysqli_connect can to return falsy value.
You should use OOP style (new mysqli) or check $conn:
$conn = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (!$conn) {
die('Connection error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
php.net - See "Procedural style" example.
It turned out it was due to variable scope.
I ended up using PHP $GLOBALS to get it to work.
I learning oop and want to use pdo to execute mysql query. I have a query inside function that I want to execute. When I do this I get an error:
Fatal error: Call to a member function exec() on a non-object
What I'am doing wrong?
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function testDuplicate($model) {
$SQL = "SELECT product_id FROM " . DB_PREFIX . "product WHERE model LIKE '" .$model . "'";
$result = $conn->exec($SQL);
if ($result->rows) return false;
return true;
}
function testDuplicateCat($cat) {
$SQL = "SELECT category_id FROM " . DB_PREFIX . "category WHERE category_id = '" .$cat . "'";
$result = $conn->exec($SQL);
if ($result->rows) return false;
return true;
}
foreach ($xml->PRODUCT as $child) {
if(testDuplicate($child->ID)){
...
}
}
This issue is raised because the $conn variable inside the testDuplicate function is not defined inside the scope of the function.
You could do this:
function testDuplicate($model) {
global $conn;
...
}
However it is not advice able to do so, its better to use static variables.
function getconn(){
static $conn;
if(!isset($conn)){
$conn = new PDO(...);
}
return $conn;
}
function foobar(){
$result = getconn()->query($sql);
while($row = $result->fetch()){
$ids[] = $row['category_id'];
}
return sizeof($ids) > 0 ? $ids : false;
}
if(($list = foobar()) == false){
echo "products " . var_export($list) . ' are duplicate values';
}
Why? Because you cannot simply overwrite the connection variable, even by accident or by using someone elses code. There are better alternatives but this is just a quick and safe example.
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;
}
?>
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.