php add prepared statements to database - php

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

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.

Best practices / most practical ways to implement mysqli connections

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.

connection with database with OOP mysqli extending class

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.

function within a function returning an object not working

I have some code which works:
$user = 'xxx';
$pass = 'xxx';
$db='vive';
$host ='localhost';
$name = 'chris';
function test($user, $pass, $db, $host){
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
else{
echo 'Checkpoint 1.0 <br>';
return $mysqli;
}
}
$mysqli2 = test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli2->query($sql);
$num_results = $result->num_rows;
if ($result->num_rows>0) ...
I am able to connect to the database and pull the information that I want out of the database everytime. I wanted to clean up my code a little (all the details are not shown), so i made a new function register() out of the last part of the code. In this new function, i want to call on function test() to return me a database connection object which I can then use to perform queries:
<?php
$user = 'root';
$pass = 'root';
$db='vive';
$host ='localhost';
$name = 'chris';
function test($user, $pass, $db, $host){
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
else{
echo 'Checkpoint 1.0 <br>';
return $mysqli;
}
}
function register($name){
echo'test';
global $user;
global $pass;
global $db;
global $host;
$mysqli2 = test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli2->query($sql);
$num_results = $result->num_rows;
if ($result->num_rows>0)...
}
For some reason the function register() will never give me any values from the database. I am unable to get anything for $result. Any help is appreciated, I have been dancing around the problem for a few days now. Note that in my actual code I have these two functions in different php files.
The LIKE statement there in the query is missing %...% wrapper.
change the register to :
function register($name){
global $user;
global $pass;
global $db;
global $host;
$name = "%".$name."%"; // see here..
echo'test';
$mysqli2 = test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli2->query($sql);
$num_results = $result->num_rows;
if ($result->num_rows>0)...
}
and make sure the method is called
Why the where username like?
shouldn't it be where username = ?
also the quotes you used are redundant.
$sql = "SELECT * FROM vive_user WHERE username LIKE"."'$name'";
could just be
$sql = "SELECT * FROM vive_user WHERE username = '$name'";

AMFPHP 2.2 backoffice call simple works but call amf returns null?

in back office when calling simple everything is fine all i have to do is fill in the appropriate field with a UID(userid) but when i use call AMF it returns null
<?php
class Gotoandlearn
{
public function __construct()
{
//mysql_connect("server", "username", "password");
//mysql_select_db("database");
}
/**
* Retrieves tutorial data
* #returns title, description, and url
*/
function getTutorials($myId)
{
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Name, Map FROM xxx WHERE Uid=$myId";
// $sql = "SELECT Uid, Name, Map FROM xxx";
$result = $conn->query($sql);
// Check connection
if ($result->num_rows > 0) {
return $result;
} else {
echo false;
}
$conn->close();
//return mysql_query("SELECT title, description, url FROM Tutorials");
}
}
?>
With Amfphp you can't return a resource. Best practice is to use PDO http://php.net/manual/en/book.pdo.php which returns an object or an array that be can be sent back.
You can see some sample code here https://github.com/silexlabs/amfphp-2.0/blob/master/Examples/Php/ExampleServices/UserService.php

Categories