$this->con->prepare not working - php

i have config file for connection but when ever i use $this->con->prepare() or $this->con->query() are not working.
But when i make separate variable for connection its work fine below are example.
this code in not working
private function isEmailexist($email)
{
$stmt = $this->con->prepare("SELECT * FROM devices WHERE email = ?");
$stmt->bind_param("s",$email);
$stmt->execute();
$stmt->store_result();
$rows = $stmt->num_rows;
echo "Rows : ".$rows;
}
This code work
private function isEmailexist($email)
{
$mysqli = new mysqli("localhost", "root", "", "demo1");
$stmt = $mysqli->prepare("SELECT * FROM devices WHERE email = ?");
$stmt->bind_param("s",$email);
$stmt->execute();
$stmt->store_result();
$rows = $stmt->num_rows;
echo "Rows : ".$rows;
}
this is config file
class Config
{
private $con;
function __construct(){}
function connect()
{
define('DB_USERNAME','root');
define('DB_PASSWORD','');
define('DB_NAME','demo1');
define('DB_HOST','localhost');
$con = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "Connection success...";
return $this->con;
}
}

Your issue is with setting $con inside of connect()
You are using
// $con is only visible within the scope of the connect function
$con = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
but it should be
// this will set the config class's $con property so that it is re-usable
$this->con = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);

Related

How to use a created database class to query data from MySQL database

I have difficulties to select data, and even to put data in my database when I use classes. Here are two examples, one works (without classes) and the other does not (with classes).
Let's start with the one that works.
In the file name index1.php we have these code lines.
$con = new PDO("mysql:host=localhost;dbname=database","user","pass");
echo "Connection success ";
$sql = "SELECT email FROM users WHERE email=:email";
$email= "mail#gmail.com";
$stmt = $con->prepare($sql);
//var_dump($stmt);
$stmt->bindParam(":email", $email, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
echo $count;
This returns $count = 2, which is true. I have 2 users in the database with mail#gmail.com as email.
Now to the case that does not work.
This is the file Database.php
<?php
class Database{
protected $pdo;
protected static $instance;
protected function __construct(){
$this->pdo = new PDO("mysql:host".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
echo "success";
}
public static function instance(){
if(self::$instance===null){
self::$instance = new self;
}
return self::$instance;
}
public function __call($method, $args){
return call_user_func_array(array($this->pdo, $method), $args);
}
}
?>
And I use it in the file index2.php
define("DB_HOST", "localhost");
define("DB_USER", "user");
define("DB_PASS", "pass");
define("DB_NAME", "database");
include_once "Database.php";
$pdo = Database::instance();
$sql = "SELECT email FROM users WHERE email=:email";
$email = "mail#gmail.com";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":email", $email, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
echo $count;
This $count returns 0.And I get no error. I used var_dump() and $stmt->debugDumpParams() but could not found where the problem is). Am I doing something wrong ?

MySQLi Prepare Statement and OOP PHP Query Returns 0 Row

Trying to get data from MySQLi using PHP OOP apporoach I am getting No rows while I am sure I have match row in the database
I have a class called db stored in a file as db.inc.php and it is like
<?PHP
class db {
private $DBSERVER;
private $DBUSERNAME;
private $DBPASSWORD;
private $DBNAME;
protected function connect(){
$this->DBSERVER = "localhost";
$this->DBUSERNAME = "root";
$this->DBPASSWORD = "";
$this->DBNAME = "maator";
$conn = new mysqli($this->DBSERVER, $this->DBUSERNAME, $this->DBPASSWORD, $this->DBNAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
}
?>
I have an extended class called SetData in SetData.inc.php which like
<?PHP
include_once('db.inc.php');
class SetData extends db {
private $page;
private $region;
private $conn;
function __construct() {
$this->conn = new db();
}
public function SetBox($vpage, $vregion){
$this->page = $vpage;
$this->region = $vregion;
$stmt = $this->conn->connect()->prepare("SELECT `title`,`description` FROM html WHERE `page` = ? AND `region` = ?");
$stmt->bind_param("ss", $this->page, $this->region);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows === 0) exit('No rows');
$stmt->bind_result($titlerow,$descriptionrow);
$stmt->fetch();
$title = $titlerow;
$description = $descriptionrow;
$stmt->free_result();
$stmt->close();
}
}
?>
and finally in front page I have
<?PHP
$page = 'game';
$region = 'ASIA';
include '../inc/SetData.inc.php';
$cls = new SetData();
$cls->SetBox($page, $region);
I don't know what dbconnect() is, you need to call your connect() method here:
//$this->conn = new dbconnect(); // NO!
$this->conn = $this->connect();
Also, you shouldn't call connect() here, you already have a connection in $conn:
//$stmt = $this->conn->connect()->prepare("SELECT `title`,`description` FROM html WHERE `page` = ? AND `region` = ?"); // NO!
$stmt = $this->conn->prepare("SELECT `title`,`description` FROM html WHERE `page` = ? AND `region` = ?");
Then, what do you want to do with $title and description? Maybe return them?
$stmt->bind_result($titlerow, $descriptionrow);
$stmt->fetch();
$stmt->free_result();
$stmt->close();
return array('title' => $titlerow, 'description' => $descriptionrow);
Then call SetBox() and display:
$result = $cls->SetBox($page, $region);
echo $result['title'];
Or set properties:
$stmt->bind_result($titlerow, $descriptionrow);
$stmt->fetch();
$this->title = $titlerow;
$this->description = $descriptionrow;
$stmt->free_result();
$stmt->close();
Then call SetBox() and display:
$cls->SetBox($page, $region);
echo $cls->title;

Cannot retrieve records using the database class.

This is a database class which connects to the database taking in the host name, username, password and the databasename. The MembersModel class after the DatabaseConnect class, which also extends the DatabaseConnect, is supposed to retrieve information.
<?php
class DatabaseConnect
{
protected $conn;
protected $host, $username, $password, $database;
public function __construct($host, $username, $password, $database){
// Create connection
$this->conn = new mysqli($host, $username, $password,$database)
OR die("There was a problem connecting to the database");
return true;
}
public function query($sql) {
$result = $this->conn->query($sql);
if (!$result) {
die('Invalid query:');
}
return $result;
}
public function __destruct(){
$this->conn->close()
OR die("Problem disconnecting from the database");
}
}
class MemberModel extends DatabaseConnect
{
public function getAllMembers() {
$result = $this->query("SELECT * FROM members");
return $result;
}
}
To connect and retrieve from the database this is what I have been trying to do
$db = new DatabaseConnect("localhost", "root", "", "pcaframework");
$allMembers = $db->getAllMembers();
while ($row = mysqli_fetch_assoc($allMembers)) {
echo "First Name: " . $row['name'] ."<br />";
echo "Last Name: " . $row['email'] ."<br />";
echo "<hr />";
}
but this is what I get "Fatal error: Call to undefined method DatabaseConnect::getAllMembers()". Can you point out the problem here.
Your $db object should be an instance of MemberModel. The DatabaseConnect class does not contain the getAllMembers function.
Change
$db = new DatabaseConnect("localhost", "root", "", "pcaframework");
To
$db = new MemberModel("localhost", "root", "", "pcaframework");

php add prepared statements to database

I want to implement the prepared statement to my script but really cant get it to work. I already have alot of functions so i want as little change as possible.
I think it would be best to have a prepared statement function? So when i get user inputs I could call that functions instead of query.
The database.php class
class MySQLDB {
var $connection; // The MySQL database connection
/* Class constructor */
function MySQLDB() {
global $dbsystem;
$this->connection = mysqli_connect ( DB_SERVER, DB_USER, DB_PASS, DB_NAME ) or die ( 'Connection Failed (' . mysqli_connect_errno () . ') ' . mysqli_connect_error () );
}
/**
* query - Performs the given query on the database and
* returns the result, which may be false, true or a
* resource identifier.
*/
function query($query) {
return mysqli_query ( $this->connection, $query );
}
};
/* Create database connection */
$database = new MySQLDB ();
this is how I call the database from another class.
$q = "UPDATE users SET name = '$name', started = '$time' WHERE id = '$id';";
$result = mysqli_query ( $database->connection, $q );
In your case I would do something a little cleaner, like this:
<?php
class MySQLDB{
private function openConnection(){
// If you don't always use same credentials, pass them by params
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Assign conection object
return $conn;
}
private function closeConnection($conn){
$conn->close();
}
function updateUserById($id, $name, $startedTime){
$conn = $this->openConnection();
$sqlQuery = "UPDATE users SET name = ?, started = ? WHERE id = ?";
if ($stmt = $conn->prepare($sqlQuery)) {
// Bind parameters
$stmt->bind_param("ssi", $name, $startedTime, $id);
// Execute query
$stmt->execute();
if ($stmt->errno) {
die ( "Update failed: " . $stmt->error);
}
$stmt->close();
}
$this->closeConnection($conn);
}
} // Class end
Now, to use it, you just have to do this:
<?php
$myDBHandler = new MySQLDB;
$myDBHandler->updateUserById(3, "Mark", 1234);

Connect to DB and Activites by OOP in PHP

Hi I am having some issues connecting to my DB using OO PHP. My script is below. I have been going at this for a while now. This is just a test script as I am fairly new to OOP. Please don't be harsh
class Database{
public $mysqli,
$host,
$username,
$password,
$db;
public function __construct($host, $username, $password, $db){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$mysqli = new mysqli($host, $username, $password, $db);
if (!$mysqli){
echo "error in connecting to database";
}
else{
echo "success in connecting to database";
}
}
public function query(){
$result = $mysqli->query("SELECT * FROM inventory");
if ($result) {
printf("Select returned %d rows.\n", $result->num_rows);
$result->close();
}
else{
echo "there is an error in query";
$result->close();
}
//echo "in query function";
}
}
Usage...
$DB = new Database('localhost', 'root', 'xxxx', 'yyyy');
$DB -> query();
Your main problem is that you aren't storing a value into your class' $mysqli property. You need to use $this->mysqli in your constructor and query method instead of $mysqli.
Secondly, this class adds nothing that the mysqli class doesn't already have. You might as well simply use
$DB = new mysqli('localhost', 'root', 'xxxx', 'yyyy');
if ($DB->connect_error) {
throw new Exception($DB->connect_error, $DB->connect_errno);
}
The problem is, you are accessing the class property without $this. The $mysqli should be in $this->mysqli in constructor function.
You are using mysqli property as Object of mysqli class.
Then you can use the query function of mysqli property object(In Database class) by $this->mysqli->query("SELECT * FROM inventory") in query function.
Updated Code:
<?php
class Database{
public $mysqli,
$host,
$username,
$password,
$db;
public function __construct($host, $username, $password, $db){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->mysqli = new mysqli($host, $username, $password, $db);
/* check connection */
if ($this->mysqli->connect_errno) {
printf("Connect failed: %s\n", $this->mysqli->connect_error);
exit();
} else {
echo "success in connecting to database";
}
}
public function query(){
$result = $this->mysqli->query("SELECT * FROM inventory");
if ($result) {
printf("Select returned %d rows.\n", $result->num_rows);
$result->close();
}
else{
echo "there is an error in query";
$result->close();
}
//echo "in query function";
}
}
$DB = new Database('localhost', 'root', 'xxxx', 'yyyy');
$DB -> query();
Try this:
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection succeeded
if(mysqli_connect_error()){
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}

Categories