Cannot call MySQL when including class in PHP - php

I've got a problem with include. I'm doing some kind of blog, and at this moment it looks like this:
index.php
article.php
class/art.class.php
Let's focus on article.php, which looks like this:
<?php
$mysqli = new mysqli("","","",""); // here are my connection details
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$mysqli->query("SET NAMES 'utf8'");
require("class/art.class.php");
$art = new Article();
print_r($art->get_art(trim($_GET['id'])));
$mysqli->close();
?>
And art.class.php is like this:
<?php
class Article {
function get_art($id) {
if(!is_numeric($id)) {
header("Location: index.php");
die("<h2>ID isn't numeric, cannot go on.</h2>'");
}
if($result = $mysqli->query("SELECT * FROM `articles` WHERE id='$id';")) {
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$art = $row;
}
$result->close();
}
return $art;
}
}
?>
The problem is a response from MySQL. Sorry, I mean no response. And no errors. I figured out that I need to add mysql connection code to class code. But why? How I can connect once to database and call it from anywhere, even from included class?
And sorry if my english is bad..

The get_art function within the Article class does not have access to variables outside of it's scope: please see the answer here.
In order to fix your issue, you may provide access to the $mysqli object by passing it to the constructor of the Article class when you instantiate it:
Article.php:
$mysqli = new mysqli("","","",""); // your connection details
$art = new Article($mysqli);
art.class.php:
class Article {
protected $mysqli;
public function __construct($mysqli) {
$this->$mysqli = $mysqli;
}
function get_art($id) {
// Replace $mysqli with $this->mysqli everywhere you need to
// make database calls
}
}

Although some would recommend that you avoid doing so, you could use PHP's $GLOBALS variable to store your database connection:
$mysqli = new mysqli("","","",""); // here are my connection details
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$GLOBALS['mysql'] = $mysqli;
This way you would have access to it within your class:
class Article
{
function get_art($id)
{
$mysqli = $GLOBALS['mysqli'];
...
}
}

Related

problem with "real_escape_string"

i am having some troubles my the "real_escape_string" and i need some help
login.php
<?php include('Connections/local.php'); ?>
<?php
function GetSQLValueString($sql) {
$sql = $mysqli->real_escape_string($sql);
return $sql;
}
?>
local.php
<?php
$hostname_local = "xxx";
$database_local = "xxx";
$username_local = "xxx";
$password_local = "xxx";
$mysqli = new mysqli($hostname_local, $username_local, $password_local, $database_local);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
the error is
Undefined variable: mysqli
i've tried some things ( like moving the content of the local.php inside the login.php ) but nothing works
You can't access $mysqli inside your function.
If you want to, add global $mysqli; in your function to make it accessible. Alternatively, you could pass the $mysqli as a parameter.
Why not just use the function call directly.
My suggestion, just create a simpler (and easier to read function) called "esc" and use that anytime you need to escape anything sql related.
function esc($string, $mysqli = false) {
if (!$mysqli) global $mysqli;
return mysqli_real_escape_string($mysqli,$string);
}
And then just use this by doing the following:
$sql = esc($string); //if $mysqli is already set globally, and thus will be inherited by the function
OR
$sql = esc($string,$mysqli); //if $mysqli is to be passed into each func call

Query after connecting to remote MySQL database using mysqli_real_connect

I can successfully connect to a remote MySQL database using mysqli_init(), mysqli_ssl_set and mysqlii_real_connect. I can't seem to find an example of a query being done after connecting. The result of mysqli_real_connect is a boolean value, whereas mysqli_connect returns an object representing the connection to the MySQL server. How do I refer to the connection after using mysqli_real_connect? Can anyone provide an example?
<?php error_reporting(E_ALL);
ini_set("display_errors", "1");
$obj = mysqli_init();
mysqli_options($obj, MYSQLI_OPT_CONNECT_TIMEOUT, 5);
mysqli_ssl_set( $obj,
NULL,
NULL,
'ca-cert.pem',
NULL,
NULL);
$link = mysqli_real_connect($obj, 'xxxxxxxxxxxx.com', 'user', 'password, 'database_name');
if (!$link)
{
die('<br /><br />Connect Error (' . mysqli_connect_errno() . ') '.mysqli_connect_error());
} ?>
The way that you'd do it using your example is mysqli_query($obj, QUERY HERE);
However, you should consider using the OOP (Object Orientated Programming) style, as that would be easier for you to reference within the future.
<?php
Class Database {
private $obj;
public function __construct() {
$this->obj = new mysqli('xxxxxxxxxxxx.com', 'user', 'password', 'database_name');
if (!$this->obj) {
die('<br /><br />Connect Error (' . mysqli_connect_errno() . ') '.mysqli_connect_error());
}
}
public function query($query) {
return $this->obj->query($query);
}
}
?>
You would call this class by doing:
$db = new Database();
And from there on, you could simply call your function by using the following example.
$db->query("SELECT * FROM users"); // or whatever query you are parsing.

How to use PHP classes between other classes [duplicate]

This question already has answers here:
What is dependency injection?
(37 answers)
Closed 9 years ago.
I know the basics of PHP and have only ever used it to debug WordPress code generally, but now I want to write my own little program to download an email and process an attachment and I have decided to try using classes as I have a basic understanding of OO programming.
SO PLEASE READ: I am a novice! I don't know what on earth dependency injection is or means...
My issue is that I have created a function called printStatus(), so I can toggle on/off output of comments. I was looking at this, and I'm not sure how or if it would fit into a class structure or if I need to include this function in every other class I create?
Basically - If I created a class, I would need to make it available to all other classes (i.e. a global class) but I'm not sure if that is achievable.
My questions are:
Do I have to pass a reference to the printOutput class to and from every class I use to have it available to me OR can I declare it globally to make it available to all classes OR do I need to include the same function in every class I create?
I've created a MySQL Connection class and I am passing that into each object for use - should (can I) declare it globally and just make it available to all classes?
Thanks for the 101.
Here is my code, am I going down the right path?: (see specifically, references to printStatus())
PS - $formatoutput->printStatus() does not work within other classes - I'm looking to understand what structure is required to make it work.
class.formatoutput.php:
class formatOutput {
var $debug = true;
function printStatus($text, $html = true) {
if ($debug) {
echo $text;
echo $html?"<br/>\n":"\n";
}
}
function printObjectStatus($object, $html = true) {
if ($debug) {
echo '<pre>';
echo $text;
echo $html?"</pre><br/>\n":"</pre>\n";
}
}
}
class.connection.php:
class Connection
{
var $db_host = "host";
var $db_name = "name";
var $db_user = "user";
var $db_pass = "pass";
var $db_conn;
function connectToDatabase() {
$db_conn = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
if (!$db_conn) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
else
{
$this->db_conn = $db_conn;
$formatoutput->printStatus( "Connection established");
}
return $this->db_conn;
}
function closeConnection() {
mysqli_close($this->db_conn);
$formatoutput->printStatus( "Connection closed");
}
}
class.customer.php:
class Customer {
var $customer_id;
var $customer_name;
function getCustomer($connection, $user_id) {
$query = "SELECT id, name FROM customer WHERE user_id=$user_id";
$result = mysqli_query($connection, $query);
if($result === FALSE) {
die('Connect Error (' . mysqli_errno() . ') ' . mysqli_error());
}
$row_count = mysqli_field_count($connection);
$formatoutput->printStatus( "COUNT: (".$count.")");
}
}
index.php:
include 'class.formatoutput.php';
include 'class.connection.php';
include 'class.customer.php';
$formatoutput = new formatOutput();
$formatoutput->printStatus('Start new Connection()');
$connection = new Connection();
$connection->connectToDatabase();
$customer = new Customer();
$customer->getCustomer($connection->db_conn, "1");
$connection->closeConnection();
Declare the function printStatus as static:
static function printStatus($text, $html = true)
You can call this function by using "::",
formatOutput::printStatus("hello");

Call a method to connect to the DB with mysqli

Hi i am trying to move from MySQL to MySQLi in my PHP script, i had this system class with the function that connects to the database that i call whenever i need, with a simple method like this:
Sys::database_connect();
the actual code of the function is:
function database_connect(){
require 'conf.php';//configuration file with database variables (sql_)
mysql_connect($sql_serv, $sql_user, $sql_pw) OR die('ERRO!!! não ligou a base de dados');
mysql_select_db($sql_bd);
}
after calling the function i can query the database without problem.
But I cant do the same with mysqli if I put this in the sys class:
function database_connect(){
require 'conf.php';
$mysqli = new mysqli($sql_serv, $sql_user, $sql_pw, $sql_bd);
if (mysqli_connect_errno()) {
printf("Ligação à Base de dados falhou: %s\n", mysqli_connect_error());
exit();
}
}
When I call
Sys::database_connect();
it connects to the database but i can't query has i used to what i would like would be a simple method as I have done with normal MySQL, if somebody can explain what am I doing wrong or why exactly I cannot do it like that...
Thank you in advance;
Fernando Andrade.
Your later queries have to use the mysqli connection identifier, you create when connecting to the database. So save this to a property of your system class and use it later on.
function database_connect(){
require 'conf.php';
$mysqli = new mysqli($sql_serv, $sql_user, $sql_pw, $sql_bd);
if (mysqli_connect_errno()) {
printf("Ligação à Base de dados falhou: %s\n", mysqli_connect_error());
exit();
}
Sys::$dbConn = $mysqli;
}
and then later on
function query( $sql ) {
Sys::$dbConn->query( $sql );
// error handling etc.
}
I wrote an extend for the mysqli database class
class database extends mysqli {
function __construct() {
parent::__construct('host', 'user', 'password', 'database');
if(mysqli_connect_error()) {
die('Connect error ('.mysqli_connect_errno().')'.mysqli_connect_error());
}
parent::query("SET NAMES 'utf8'");
}
function query($query) {
$result = parent::query($query);
if(!$result) {
echo "<strong>MySQL error</strong>: ".$this->error."<br />QUERY: ".$query;
die();
}
if(!is_object($result)) {
$result = new mysqli_result($this);
}
return $result;
}
}
So connecting to database is $db = new database()
Executing a query is $db->query(YOUR QUERY);

Is it possible to use a $myqli->real_escape_string in side of a custom class with out loading the connection again?

Is it possible to use a $myqli->real_escape_string in side of a custom class with out loading the connection again? Take the code below. $mysqli is created twice is it possible to use the connection already established?
<?php
$mysqli = new mysqli('127.0.0.1','user','password','table');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit('connect failed!');
}
// connected
class save {
public $datatosave = '';
function __construct ($new) {
$mysqli = new mysqli('127.0.0.1','user','password','table');
$this->datatosave = $mysqli->real_escape_string($new);
}
}
$infromation = " ' test";
$newinfo = new save ($infromation);
echo $newinfo->datatosave;
$mysqli->close();
?>\
should still output \' test
Since you are catching the connection with the $mysqli variable, just pass that into your __construct function when you initialize the class.
class save {
public $datatosave = '';
function __construct ($new, $mysqli_attr) {
$this->datatosave = $mysqli_attr->real_escape_string($new);
}
}
$infromation = " ' test";
$newinfo = new save ($infromation, $mysqli);
echo $newinfo->datatosave;

Categories