How to use PHP prepared statements in OOP - php

I am saving my data using this code (pasting my code)
Connection.php:
<?php
namespace Database;
use Mysqli;
class Connection {
public $con;
function __construct() {
$this->con = new mysqli(connection strings here);
}
function save($sql) {
$this->con->query($sql);
}
}
?>
then my Save.php is like this:
<?php
require 'config.php';
class Save {
function __construct($username, $password) {
$connect = new Database\Connection;
$sql = "INSERT INTO sample(string1, string2) VALUES ('$test1', '$test2')";
$connect->save($sql);
}
}
$save = new Save("last", "last");
?>
my question is how do I implement bind params here and prepared statement for PHP?
and also I would like to ask what are the best way to do this and best practices that I should implement for my code
thanks guys

Your classes are structured in a weird way, I am guessing you want some sort of ORM like class?
If so, you may want to rename your Save class to User (that's a guess since you are trying to save a username and password) and move your constructor logic, e.g.
class User {
function save($username, $password) {
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
}
}

This example explain how you can do it .
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", $mysqli->affected_rows);
/* close connection */
$mysqli->close();
?>
And you can find more info in this link : http://php.net/manual/tr/mysqli-stmt.bind-param.php
And i suggest you to use PDO its better way to connect with the
database .

Use like this.
public function insert_new_user($username, $email, $password){
$mysqli = $this->link;
$sql = "INSERT INTO users"
. " (user_name, user_email, user_pass)"
. " VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sss", $username, $email, $password);
if ($stmt->execute()) {
return "success";
} else {
return "failed: " . $mysqli->error;
}
}

Related

Need help to get rid of in this PHP code that restricts me from having the same entry in a category in a database. (please help)

I need to get rid of the part that restricts me from adding the same value in a field from previous entries. I need to get rid of the part that gives me an error message if the entry matches a value from the database. Can someone please help me?
<?php
class DbOperation
{
private $conn;
//Constructor
function __construct()
{
require_once dirname(__FILE__) . '/Constants.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createUser($RC, $Date, $Value)
{
if (!$this->isUserExist($RC, $Date, $Value)) {
$password = md5($pass);
$stmt = $this->conn->prepare("INSERT INTO MyInventory (username, password, email, name, phone) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $username, $password, $email, $name, $phone);
if ($stmt->execute()) {
return ENTRY_CREATED;
} else {
return ENTRY_ALREADY_EXIST;
}
} else {
return ENTRY_ERROR;
}
}
private function isUserExist($username, $email, $phone)
{
$stmt = $this->conn->prepare("SELECT id FROM users WHERE username = ? OR email = ? OR phone = ?");
$stmt->bind_param("sss", $username, $email, $phone);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
as you can see in the photo below, every single entry in the database is different. I need to get rid of this and make it so that it is possible for 2 "RC" values to be the same.
When createUser is called, it first checks if the user already exists (if a record exists in the database with the same RC) by calling isUserExist. If you want to allow duplicate RC values, simply remove the if/else statement and only keep the code inside of the if block.

mysqli function doesn't insert values

I'm trying to connect to a database by mysqli in an object oriented way. I had a few errors, and solved them, but now I just can solve this one. I've got my code here, and all the names (database name, user, password, host, and table names) are correct (actually, copied and pasted), but the query still returns 0.
<?php
class DbConnection
{
public $link;
public function __construct()
{
$this->link = new mysqli("localhost","root","","todo");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
function RegisterUsers($username, $password, $ip, $name, $email)
{
$stmt = $this->link->prepare("INSERT INTO users (Username, `Password`, ip, Name, Email) VALUES (?,?,?,?)");
$stmt->bind_param("sssss", $username, $password, $ip, $name, $email);
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows;
return $count;
}
}
$dbConn = new DbConnection();
echo $dbConn->RegisterUsers("a","a","a","a", "a");
?>
Edit: With this code, i get an
Call to a member function bind_param() on boolean
error.
Password and name are keywords in mysql. You have to put it in backticks to escape it, if you will use it as column name
$stmt = $this->link->prepare("INSERT INTO users (Username, `Password`, ip, `Name`) VALUES (?,?,?,?)");

Binding parameters in mysql

I'm trying to learn about binding parameters in MySQL. I tried this test but I'm getting the error "Call to a member function bind_param() on a non-object".
Am I doing something wrong?
Here is the updated code:
$sql = "INSERT INTO users (field1, field2, field3) VALUES (?, ?, ?)";
connect();
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $value1, $value2, $value3);
$value1 = "test1";
$value2 = "test2";
$value3 = "test3";
$stmt->execute();
Here is the connect() function:
function connect(){
global $conn;
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
To bind params in a prepared query in PDO, pass an array containing your params to the execute function :
$result = $conn->prepare($sql);
$result->execute(array($value1, $value2, $value3));
UPDATE
For the mysqli version :
connect();
$result = $conn->prepare($sql);
$result->bind_param('sss', $value1, $value2, $value3);
$result->execute();
See http://php.net/manual/en/mysqli-stmt.bind-param.php

Mysqli commit in other function

I have a PHP class with many functions and this is my problem:
In function A i do some steps for prepare an insert into database
But I DON'T commit because I want do it in an other function (B function) like this code.
But in the data base no one row is inserted.
Any idea?
Thanks to all, this is my sample code:
public static function functionA($id, $email, $password, $name, $surname) {
global $mysqli;
$mysqli = self::getDb(); //with $mysqli->autocommit(FALSE);
if (!($stmt = $mysqli->prepare('INSERT INTO User (Id, mail, Password, Name, Surname) VALUES (?,?,?,?,?)'))){
self::closeDatabase($mysqli, $stmt);
die;
}
if (!$stmt->bind_param("sssss", $id, $email, $password, $name, $surname)) {
self::closeDatabase($mysqli, $stmt);
die;
}
if (!$stmt->execute()) {
self::closeDatabase($mysqli, $stmt);
die;
}
}
public static function functionB() {
global $mysqli;
$mysqli->commit();
self::closeDatabase($mysqli, $stmt);
}
Change this code
if (!($stmt = $mysqli->prepare('INSERT INTO User (Id, mail, Password, Name, Surname) VALUES (?,?,?,?,?)'))){
self::closeDatabase($mysqli, $stmt);
die;
}
to this one:
$sql = 'INSERT INTO User (Id, mail, Password, Name, Surname) VALUES (?,?,?,?,?)';
if (!($stmt = $mysqli->prepare($sql)))
{
throw new Exception($mysqli->error." [$sql]");
}
for ALL your queries.
Then make sure you can see PHP errors.
Then run your code again.

PHP Mysqli no errors, no querys

I'm trying to use mysqli instead of mysql queries, and it's not working.
Mysqli:
$mysqli->connect($db1['host'], $db1['user'], $db1['password'], $db1['database']);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
no errors. If I try this query:
if(isset($_POST['username']))
{
$password = $_POST['p'];
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
$password = hash('sha512', $password.$random_salt);
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
$insert_stmt->execute();
}
echo "Success";
}
nothing is inserted, no errors with mysqli error.
Table structure is correct, and it says success. I'm new to mysqli, I'm used to mysql. Is there something I've missed with error reporting?
you have to do it like this way
$password = hash('sha512', $password.$random_salt);
$insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)");
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
if($insert_stmt->execute())
{
echo "Success";
}
Actually you are first checking the query and after that binding the params, because of that it was just displaying Success.
Better try this, its from php manual
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli- >connect_error;
}
You could do the $stmt->execute(); in an if loop like this:
if ($stmt->execute()){
$result = $stmt->affected_rows;
if ($result) { echo "yay" } else { echo "boo"; }
}
else {
printf("Execute error: %s", $stmt->error);
}

Categories