connection with database with OOP mysqli extending class - php

I know must coding part of mysql bt new at mysqli. I am not able to execute these insert query to the database. I have searched a lot but couldn't find simple suggestion, or may be i didn't understand.
Undefined variable: mysqli in C:\wamp\www\New folder\php\msqliconnect.php on line 32
Fatal error: Call to a member function mysqli_query() on a non-object in C:\wamp\www\New folder\php\msqliconnect.php on line 32
Any help is appreciated.
<?php
class connection
{
public $mysqli;
function connect()
{
$hostname = "localhost";
$username = "root";
$password = "";
$database = "demodatabase";
$mysqli = new mysqli($hostname, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return true;
}
}
class Index extends connection
{
function __construct()
{
parent::connect();
}
function insertdata($a, $b)
{
// echo $a. ' ' .$b;
// MySqli Insert Query
$status = 0;
$insert_row = $mysqli->mysqli_query("INSERT INTO tb_user (id, user, password, status) VALUES('','" . $a . "', '" . $b . "', '')");
if ($insert_row)
{
print 'saved';
}
else
{
die('Error : (' . $mysqli->errno . ') ' . $mysqli->error);
}
}
}
?>

In both of your connect() and insertdata() methods, you're using local variable $mysqli, not the instance variable public $mysqli;. You should use $this->mysqli instead of $mysqli in your instance methods. So your connect() and insertdata() methods would be like this:
function connect(){
$hostname = "localhost";
$username = "root";
$password = "";
$database = "demodatabase";
$this->mysqli = new mysqli($hostname, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return true;
}
and
function insertdata($a, $b){
$insert_row = $this->mysqli->query("INSERT INTO tb_user (id, user, password, status) VALUES('','".$a."', '".$b."', '')");
if($insert_row){
print 'saved';
}else{
die('Error : ('. $this->mysqli->errno .') '. $this->mysqli->error);
}
}
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attack. Also see how you can prevent SQL injection in PHP.

Related

linking my database to my server on xampp for the first time [duplicate]

I'm working on streamlining a bit our db helpers and utilities and I see that each of our functions such as for example findAllUsers(){....} or findCustomerById($id) {...} have their own connection details for example :
function findAllUsers() {
$srv = 'xx.xx.xx.xx';
$usr = 'username';
$pwd = 'password';
$db = 'database';
$port = 3306;
$con = new mysqli($srv, $usr, $pwd, $db, $port);
if ($con->connect_error) {
die("Connection to DB failed: " . $con->connect_error);
} else {
sql = "SELECT * FROM customers..."
.....
.....
}
}
and so on for each helper/function. SO I thought about using a function that returns the connection object such as :
function dbConnection ($env = null) {
$srv = 'xx.xx.xx.xx';
$usr = 'username';
$pwd = 'password';
$db = 'database';
$port = 3306;
$con = new mysqli($srv, $usr, $pwd, $db, $port);
if ($con->connect_error) {
return false;
} else {
return $con;
}
}
Then I could just do
function findAllUsers() {
$con = dbConnection();
if ($con === false) {
echo "db connection error";
} else {
$sql = "SELECT ....
...
}
Is there any advantages at using a function like this compared to a Class system such as $con = new dbConnection() ?
You should open the connection only once. Once you realize that you only need to open the connection once, your function dbConnection becomes useless. You can instantiate the mysqli class at the start of your script and then pass it as an argument to all your functions/classes.
The connection is always the same three lines:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli($srv, $usr, $pwd, $db, $port);
$con->set_charset('utf8mb4');
Then simply pass it as an argument and do not perform any more checks with if statements.
function findAllUsers(\mysqli $con) {
$sql = "SELECT ....";
$stmt = $con->prepare($sql);
/* ... */
}
It looks like your code was some sort of spaghetti code. I would therefore strongly recommend to rewrite it and use OOP with PSR-4.

How to instantiate PDO class functionality (::prepare method) in another class

I'm refactoring my PHP code, so that the insertion of data into my database is kept separate from the class that creates the database connection. I'm trying to implement the Single Responsibility Principle, but transferring my code (for inserting data) to a separate class results in the PDO::prepare statement becoming an 'undefined method'.
I have tried to instantiate my database class ('DB.php') and pass the object to the class that inserts data ('Register.php').
The DB class:
<?php
class DB
{
public $dbServer,
$dbUsername,
$dbPassword,
$dbName,
$pdo,
$stmt;
function __construct($dbServer,
$dbUsername,
$dbPassword,
$dbName)
{
$this->dbServer = $dbServer;
$this->dbUsername = $dbUsername;
$this->dbPassword = $dbPassword;
$this->dbName = $dbName;
$this->connect();
}
public function connect()
{
try {
$this->pdo = new PDO("mysql:host=" . $this->dbServer .
"; dbname=" . $this->dbName,
$this->dbUsername,
$this->dbPassword);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
exit("Could not connect to database: " . $e->getMessage() );
}
}
}
The Register class:
<?php
class Register
{
public $pdo,
$dbh,
$stmt,
$conn;
function __construct(DB $pdo)
{
$this->pdo = $pdo;
// $this->conn = $this->pdo->connect();
}
public function register(Validate $val)
{
try {
$this->stmt = $this->pdo->prepare(
"INSERT INTO registration(firstName,
surname,
email,
username,
password,
gender,
area)
VALUES(:firstName,
:surname,
:email,
:username,
:password,
:gender,
:area)");
$this->stmt->bindParam(':firstName', $val->firstName);
$this->stmt->bindParam(':surname', $val->surname);
$this->stmt->bindParam(':email', $val->email);
$this->stmt->bindParam(':username', $val->username);
$this->stmt->bindParam(':password', $val->password);
$this->stmt->bindParam(':gender', $val->gender);
$this->stmt->bindParam(':area', $val->area);
$this->stmt->execute();
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
}
}
My Configuration file:
<?php
$dbServer = '127.0.0.1';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'assignment';
spl_autoload_register(function($class)
{
require 'classes/' . $class . '.php';
} );
$db = new DB($dbServer, $dbUsername, $dbPassword, $dbName);
$database = new Register($db);
The actual Registration page:
<?php
require('core/config.php');
if( isset($_POST['submit']) ) {
$firstName = $_POST['firstName'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$gender = $_POST['gender'];
$area = $_POST['area'];
$val = new Validate($firstName, $surname, $email, $username, $password, $gender, $area);
$val->filter();
$database->register($val);
}
?>
This implementation results in the following notice:
Fatal error: Uncaught Error: Call to undefined method DB::prepare()
Why doesn't the PDO class communicate its in-built prepare() function to my Register class? I have viewed 'Fatal error: Call to undefined method Database::prepare()' on Stack Overflow and sought to remedy my code:
$this->conn = $this->pdo->connect();
(See the commented statement in my Register class.) However, $this->conn ends up returning a NULL instead of my database connection.

PHP connection and query error: Fatal error: Call to a member function query() on null in

I'm getting the above error in regards to my statement below, tried multiple fixes from other answers in stack but continue to get the same error :(
this is part of a php code in a user registration form, would like their info to insert in the table
if($conn->query( "INSERT INTO users (FIRST_NAME, LAST_NAME, USERNAME, PASSWORD)
VALUES ('$fname', '$lname', '$uname', '$pword')")==TRUE){
echo 'Inserted';
}else{
echo 'Not Inserted';
}
i have this other code in a separate file for the $conn
function dbConnect(){
$servername = "x";
$database = "activity2";
$username = "root";
$password = "root";
// Create connection
$conn = new
mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);
} //echo "Connection successful"; //make variable global to access in other
functions global $conn; return $conn;}
First thing to do is to create the class that will return a connection:
<?php
//filename: dbConnect.php
class dbConnect
{
public function connect() {
global $conn;
$servername = "localhost";
$username = "root";
$password = "";
$database = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} //echo "Connection successful"; //make variable global to access in other
return $conn;
}
}
?>
Now you can execute your sql command in another file:
<?php
require 'dbConnect.php';
$db = new dbConnect();
$conn = $db->connect();
$nome = "Anailton";
$email = "jose#hotmail.com";
if($conn->query( "INSERT INTO clientes (NOME, EMAIL) VALUES ('$nome', '$email')")==TRUE){
echo 'Inserted';
}else{
echo 'Not Inserted';
}
?>

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);

How to connect to MySQL database in PHP using mysqli extension?

I have code like this to connect my server database:
<?php
$con = mysqli_connect("", "username", "password", "databasename");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
But it displayed "Failed to connect to MySQL", what is wrong with this code? First time I am trying it in web server, whereas my localhost worked perfectly.
mysqli_connect("","username" ,"password","databasename");//Server name cannot be NULL
use loaclhost for server name(In Loacl)
<?php
$con = mysqli_connect("localhost","username" ,"password","databasename");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Or can use MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$con = mysqli_connect($servername, $username, $password);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
EDIT 01
$servername = "localhost";
$username = "root";
$password = "";
To connect to the MySQL database using mysqli you need to execute 3 lines of code. You need to enable error reporting, create instance of mysqli class and set the correct charset.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname', 3307);
$mysqli->set_charset('utf8mb4'); // always set the charset
The parameters in the mysqli constructor are all optional, but most of the time you would want to pass at least 4 of them. In the correct order they are:
MySQL Host. Most of the time it is localhost, but if you connect to a remote host it will be some other IP address. Make sure this does not contain the http protocol part. It should either be an IP address or the URL without protocol.
Username. This is the username of your MySQL user. To connect to the MySQL server you need to have a valid user with the right privileges.
Password.
Database name. This is the MySQL database name you want to connect to.
Port. Most of the time the default port is the correct one, but if you use for example wampserver with MariaDB, you might want to change it to 3307.
Socket name. Specifies the socket or named pipe that should be used.
Unfortunately the charset is not one of these parameters, so you must use a dedicated function to set this very important parameter.
Please beware never to display the connection errors manually. Doing so is completely unnecessary and it will leak your credentials.
On unrelated note: I do not recommend to use MySQLi in a new project. Please consider using PDO, which is overall a much better API for connecting to MySQL.
Why use mysqli? Just use PDO for safer mysql connection just use:
$hostname='localhost';
$username='root';
$password='';
$dbh = new PDO("mysql:host=$hostname;dbname=dbname",$username,$password);
You should specify hostname
$con = mysqli_connect("localhost","username" ,"password","databasename");
If it returns an error like
Failed to connect to MySQL: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'
Replace localhost with 127.0.0.1.
If still you cant connect check if mysql server is actually running.
service mysqld start
Then, try the one of the following following:
(if you have not set password for mysql)
mysql -u root
if you have set password already
mysql -u root -p
$localhost = "localhost";
$root = "root";
$password = "";
$con = mysql_connect($localhost,$root,$password) or die('Could not connect to database');
mysql_select_db("db_name",$con);
<?php
$servername="";
$username="";
$password="";
$db="";
$conn=mysqli_connect($servername,$username,$password,$db);
//mysql_select_db($db);
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno($conn) . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error($conn) . PHP_EOL;
exit;
}
#session_start();
$event_name = $_POST['first_name'];
$first_name = $_POST['last_name'];
$sql = "INSERT INTO customer(first_name, last_name,) VALUES ('$first_name', '$last_name')";
$conn->query($sql);
$lastInsertId = mysqli_insert_id($conn);
?>
A better method is to keep the connection and the login parameters apart.
<?php
class Database{
protected $url;
protected $user;
protected $passw;
protected $db;
protected $connection = null;
public function __construct($url,$user,$passw,$db){
$this->url = $url;
$this->user = $user;
$this->passw = $passw;
$this->db = $db;
}
public function __destruct() {
if ($this->connection != null) {
$this->closeConnection();
}
}
protected function makeConnection(){
//Make a connection
$this->connection = new mysqli($this->url,$this->user,$this->passw,$this->db);
if ($this->connection->connect_error) {
echo "FAIL:" . $this->connection->connect_error;
}
}
protected function closeConnection() {
//Close the DB connection
if ($this->connection != null) {
$this->connection->close();
$this->connection = null;
}
}
protected function cleanParameters($p) {
//prevent SQL injection
$result = $this->connection->real_escape_string($p);
return $result;
}
public function executeQuery($q, $params = null){
$this->makeConnection();
if ($params != null) {
$queryParts = preg_split("/\?/", $q);
if (count($queryParts) != count($params) + 1) {
return false;
}
$finalQuery = $queryParts[0];
for ($i = 0; $i < count($params); $i++) {
$finalQuery = $finalQuery . $this->cleanParameters($params[$i]) . $queryParts[$i + 1];
}
$q = $finalQuery;
}
$results = $this->connection->query($q);
return $results;
}
}?>
This in combination with a database factory keeps the data separated and clean.
<?php
include_once 'database/Database.php';
class DatabaseFactory {
private static $connection;
public static function getDatabase(){
if (self::$connection == null) {
$url = "URL";
$user = "LOGIN";
$passw = "PASSW";
$db = "DB NAME";
self::$connection = new Database($url, $user, $passw, $db);
}
return self::$connection;
}
}
?>
After that you can easily make your (class based) your CRUD classes (objectname+DB)
<?php
include_once "//CLASS";
include_once "//DatabaseFactory";
class CLASSDB
{
private static function getConnection(){
return DatabaseFactory::getDatabase();
}
public static function getById($Id){
$results = self::getConnection()->executeQuery("SELECT * from DB WHERE Id = '?'", array(Id));
if ($results){
$row = $results->fetch_array();
$obj = self::convertRowToObject($row);
return $obj;
} else {
return false;
}
}
public static function getAll(){
$query = 'SELECT * from DB';
$results = self::getConnection()->executeQuery($query);
$resultsArray = array();
for ($i = 0; $i < $results->num_rows; $i++){
$row = $results->fetch_array();
$obj = self::convertRowToObject($row);
$resultsArray[$i] = $obj;
}
return $resultsArray;
}
public static function getName($Id){
$results = self::getConnection()->executeQuery("SELECT column from DB WHERE Id = '?'", array($Id));
$row = $results->fetch_array();
return $row['column'];
}
public static function convertRowToObject($row){
return new CLASSNAME(
$row['prop'],
$row['prop'],
$row['prop'],
$row['prop']
);
}
public static function insert ($obj){
self::getConnection()->executeQuery("INSERT INTO DB VALUES (null, '?', '?', '?')",
array($obj->prop, $obj->prop, $obj->prop));
}
public static function update ($propToUpdate, $Id){
self::getConnection()->executeQuery("UPDATE User SET COLTOUPDATE = ? WHERE Id = ?",
array($propToUpdate, $Id));
}
}
And with this fine coding it's a piece of cake to select items in frontend:
include 'CLASSDB';
<php
$results = CLASSDB::getFunction();
foreach ($results as $class) {
?>
<li><?php echo $class->prop ?><li>
<php } ?>
The easiest way to connect to MySQL server using php.
$conn=new mysqli("localhost", "Username", "Password", "DbName");
if($conn->connect_error)
{
die("connection faild:".$conn->connect_error);
}
echo "Connection Successfully..!";
localhost like this (MySQLi Procedural)
<?php
$servername ="localhost";
$username="username";//username like (root)
$password="password";//your database no password. (" ")
$database="database";
$con=mysqli_connect($servername,$username,$password,$database);
if (!$con) {
die("Connection failed: " . MySQL_connect_error());
}
else{
echo "Connected successfully";
}

Categories