Mysqli commit in other function - php

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.

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.

How to use PHP prepared statements in OOP

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

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 (?,?,?,?)");

PHP pdo insert query not working

<?php
// DATABASE-HOSTNAME-OR-IPADDRESS-GOES-HERE
// MYSQL-DBNAME-GOES-HERE
class LoginHandler {
public $dbHostname = 'localhost';
public $dbDatabaseName = 'employee101';
public $user = 'root';
public $password = 'root';
public function handleRequest($arg) {
$username = '123';
$password2 = '123';
$fname = 'John';
$lname = 'Doe';
$age = '18';
if ( ! $username ) {
$this->fail();
return;
}
try {
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$sql="SELECT * FROM `employee_data` WHERE `username`='$username'";
$stmt = $pdo->query($sql);
if ( $stmt === false ) {
echo "DB Critical Error";
return;
}
elseif ( $stmt->rowCount() > 0 ) {
echo "user already exists";
return;
}
else {
echo "User created";
$sql = "INSERT INTO employee_data (name, sumame, age, username, password)
VALUES ($fname, $lname, $age, $username, $password2)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam($fname, $_POST[$fname], PDO::PARAM_STR);
$stmtz->bindParam($lname, $_POST[$lname], PDO::PARAM_STR);
$stmtz->bindParam($age, $_POST[$age], PDO::PARAM_STR);
$stmtz->bindParam($username, $_POST[$username], PDO::PARAM_STR);
$stmtz->bindParam($password2, $_POST[$password2], PDO::PARAM_STR);
$resultzzx = $stmtz->execute();
return;
}
}
catch(PDOException $e) {
$this->log('Connection failed: ' . $e->getMessage());
echo "DB Critical Error";
}
}
function log($msg) {
file_put_contents("login.log", strftime('%Y-%m-%d %T ') . "$msg\n", FILE_APPEND);
}
}
$handler = new LoginHandler();
$handler->handleRequest($_POST);
?>
When attempting to use this script above, I get the echo that the user was created, but even when refreshing the table, the new entry doesn't show up.
Now, if i change the values line to be the following, it will work and show the new entry.
('John', 'Doe', '18', $username, $password2)";
What am i doing wrong? I need the first name, last name and age entries to not be concrete, as i will be obtaining them from a POST on my android device. The whole purpose of this script is to create the user and it's records if it doesn't already exist.
You have various mistakes.
1) You are not binding your parameters correctly. To bind them correctly, you place a :variablename in the position you want to include the variable. Usually the "variablename" should be the same as the one you are obtaining from the $_POST superglobal so that the code is cleaner and more readable.
2) You are not obtaining the values from the $_POST superglobal correctly. The key values you place inside are strings, and by placing an empty $fname variable, you are not going to obtain a correct result. It would only work if you had coding saying $fname = 'fname' somewhere up top hidden from us, however that code itself would be unadvised since it is unnecessary and only makes the source code larger.
$sql = "INSERT INTO employee_data (name, sumame, age, username, password)
VALUES (:fname, :lname, :age, :username, :password2)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host=
{$this>dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam(':fname', $_POST['fname']);
$stmtz->bindParam(':lname', $_POST['lname']);
$stmtz->bindParam(':age', $_POST['age']);
$stmtz->bindParam(':username', $_POST['username']);
$stmtz->bindParam(':password2', $_POST['password2']);
I hope that helps.
$sql = "INSERT INTO employee_data (name, sumame, age, username, password) VALUES (:name, :sumame, :age, :username, :password)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam(':name', $fname);
$stmtz->bindParam(':sumame', $lname);
$stmtz->bindParam(':age', $age);
$stmtz->bindParam(':username', $username);
$stmtz->bindParam(':password', $password2);
$resultzzx = $stmtz->execute();
return;
After reviewing the link Fred posted in the comment above, i've modified it to work fine, thanks.

Trying to take data from form and insert into database using PDO

I am trying to submit data from a form and have the data be inserted into my database using PDO. I am unsure what i am doing wrong at this point and could use any help that i can get.
Here is the code for connecting to my db
<?php
function connect(){
$config = array(
'$username' => 'root',
'$password' => 'root'
);
try {
$conn = new PDO('mysql:host=localhost;dbname=data', $config['$username'], $config['$password']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'COME GET SOME IT WORKED!!!!';
}
catch(PDOException $e) {
print "Error!";
exit;
}
}
?>
Here is the code for handling the form data
<?php
// We will include connection file first
include('functions.php');
connect();
// check if varaibable is set and Add Rate Button pressed.
if(isset($_POST["submit"])){
echo 'COME GET SOME';
// Define Variables
$firstname = $_POST[firstName]; //firstName
$lastname = $_POST[lastName]; //LastName
$email = $_POST[emailAddress]; //Email Address
$age = $_POST[age]; //Age
// We Will prepare SQL Query
$STM = $dbh->prepare("INSERT INTO 'EmailList'(id, firstName, lastName, emailAddress, age) VALUES (NULL, :firstname, :lastname, :email, :age)");
// bind paramenters, Named parameters always start with colon(:)
$STM->bindParam(':firstname', $firstname);
$STM->bindParam(':lastname', $lastname);
$STM->bindParam(':email', $email);
$STM->bindParam(':age', $age);
// For Executing prepared statement we will use below function
$STM->execute();
// We use header here for redirecting it to other page where we will show success message.
header( "location:index.php");
}
?>

Categories