I'm trying to get the id value from a table called usuario in the database, passing $username as parameter, the function $conexion->connect() returns a mysqli object. The functions give me no errors but it doesn't return the value from database. Am I missing something? or making any mistake.
Thanks for help.
public function checkUserNameExists($username){
$conexion = new Connection();
$conexion->connect();
$query = "select id from usuario where username = ?";
$reg = 0;
$stmt= $conexion->connect()->prepare($query);
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch()){
$reg = $id;
}
$stmt->close();
return $reg;
}
This is the function connect() what is located in a class file "Connection"
public function connect(){
$mysqli = new mysqli($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return $mysqli
}
public function checkUserNameExists($username){
$conexion = new Connection();
$conn = $conexion->connect();
$query = "select id from usuario where username = ?";
$reg = 0;
$stmt= $conn->prepare($query);
$stmt->bind_param('s',$username);
$stmt->execute();
$stmt->bind_result($id);
while($stmt->fetch()){
$reg = $id;
}
$stmt->close();
return $reg;
}
You should store the return value of new mysqli in a variable, and then use that variable to make queries or prepares from.
Related
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 ?
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;
i am new to this so dont be rude :D
I have 3 file: database.php, init.php and user.php
Here the init.php:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
require 'database.php';
require 'functions/user.php';
$errors = array();
Here the database.php:
<?php
$db_host = "localhost";
$db_name = "xxxx";
$db_user = "xxxx";
$db_pw = "xxxx";
try {
$conn = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_pw);
} catch(PDOException $e) {
die("Verbindung fehlgeschlagen: " . $e->getMessage());
}
And here the user.php:
<?php
function userExists($user) {
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}
So the error message:
Notice: Undefined variable: conn in /mnt/web109/b2/35/57848035/htdocs/includes/functions/user.php on line 4 Fatal error: Call to a member function prepare() on null in /mnt/web109/b2/35/57848035/htdocs/includes/functions/user.php on line 4
The function userExists() is called in another file named login.php. In login.php i have already required init.php. The error message appears when i want to login.
So i hope you can help me.
Thx
$conn is not available in your function since it is in a different scope. Pass it as a parameter or declare it as a global variable.
function userExists($user, $conn){
// ...
}
or
function userExists($user){
global $conn;
// ...
}
In your userExists function you are calling $conn variable which isn't global scope (Give a small look here)..
You can use one of these:
function userExists($user, $conn){
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}
OR
function userExists($user){
global $conn; //<--- bad practi
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}
OR
use of $GLOBALS variable
function userExists($user){
$sql = "SELECT * FROM user WHERE email = :email";
$stmt = $GLOBALS['conn']->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0) return true;
return false;
}
I want to CRUD using PDO Connection
I know how to create insert update and delete using msql_query() but I have no idea how to do that with PDO Connection.
Below is the example of that
class connection{
public $cnn;
public function __construct(){
$host = 'localhost';
$db_name = "db_name";
$username = "db_username";
$password = "db_password";
try {
$this->cnn = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function select($query){ //this function is created for get data
$result = $this->cnn->query($query);
return $result->fetchAll(PDO::FETCH_ASSOC);
}
public function insert($query){ //this function is created for insert data. it will be return last inserted id.
$this->cnn->exec($query);
return $this->cnn->lastInsertId();
}
public function update($query){ //this function is created for update data and it will be return effected rows (which are updated)
return $this->cnn->exec($query);
}
public function delete($query){ // this function is use to delete data.
return $this->cnn->exec($query);
}
}
$action = new connection;
$result = $action->select("select * from table_name");
print_r($result);
$result = $action->insert("insert into table_name set column_1 = 'first_value', column_2='second_value'");
$result = $action->update("update table_name set column_1 = 'first_value', column_2='second_value' where id=1");
$result = $action->delete("delete from table_name where id=1");
Maybe this is an easier way to do it. now the only thing you have to do is call the functions. Enjoy (:
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "database";
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function updateuser($pdo, $username, $password, $id){
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password, $id]);
}
function deleteuser($pdo, $id){
$sql = 'DELETE FROM users WHERE id = ?';
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
}
function createuser($pdo, $username, $password){
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password]);
}
function readuser($pdo, $id){
$sql = "SELECT id, username FROM users WHERE id=?";
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
I am writing following code to fetch a row from table:
$query = "SELECT ........FROM ............WHERE........AND ID = ?";
$conn = new Connection();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
echo 'Num rows = '.$stmt->num_rows();
Here's the code for Connection();
define('SERVER', 'localhost');
define('USER', 'root');
define('PASS', 'xxx');
define('DB', 'xxx');
class Connection{
var $mysqli = null;
function __construct(){
try{
if(!$this->mysqli){
$this->mysqli = new MySQLi(SERVER, USER, PASS, DB);
if(!$this->mysqli)
throw new Exception('Could not create connection using MySQLi', 'NO_CONNECTION');
}
}
catch(Exception $ex){
echo "ERROR: ".$e->getMessage();
}
}
}
If I echo the query and run it on Navicat with ID equal to the value of $_SESSION['id'], it does return me a row. But on the web-page, it show output as:
Num rows = 0
What's wrong with the code? Plz note that echo $_SESSION['id'] displays the value.
Thanks
Store your result set with store_result(), then access $stmt->num_rows as a property, not a method. (don't use ())
$query = "SELECT ........FROM ............WHERE........AND ID = ?";
$conn = new Connection();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
// Call store_result() before accessing num_rows()
$stmt->store_result();
// And access num_rows as a property, not a method
echo 'Num rows = '.$stmt->num_rows;