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 (?,?,?,?)");
Related
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.
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;
}
}
I cant get insert into database and bind_param to work.
$query="INSERT INTO user (UserName,email,Password) VALUES ('?','?','?')";
$inst=$this->db->prepare($query);
$inst->bind_param("sss",$username,$email,$password);
if(!$inst) {
echo "Query Prep Failed: %s\n", $conn->error;
exit;
}
$username="";
$email="";
$password="";
$inst->execute();
Be sure that you use a instance of mysqli:
$mysqli = new mysqli("host", "user", "password", "database");
$stmt = $mysqli->prepare("INSERT INTO user (UserName, email, Password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $email, $password);
$stmt->execute();
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.
I have this in db.php page:
function db_connect(){ $link = new mysqli(localhost, user, pass, table); }
And this is in other page:
require_once("db.php");
function register($username, $email, $password){
global $link;
$query = "INSERT INTO proyecto.user (username, password, email)
VALUES ('$username', '$password', '$email')";
$result = mysqli_query($link, $query);
}
But it doesn't work when I call "register". How should I call the function "db_connect"?
You can do it like this (PDO connection):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host , $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
You can make it become a global variable if you want.
$GLOBALS['db'] = $db;
Note that this is pdo, an example of a PDO database operation for your case, note that this uses prepared statements and is therefor quite safe from sql injections, and is quite easy to use:
function register($username, $email, $password){
$query = "INSERT INTO user (username, password, email) VALUES (:username, :password, :email)"; // Construct the query, making it accept a prepared variable search.
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':username' => $username,
':password' => $password,
':email' => $email
)); // Here you insert the variable, by executing it 'into' the prepared query.
if($result)
{
return true;
}
return false
}
And you can call it like this:
$registerSuccess = register($username, $email, $password);
have db_connect() return the $link, or make $link global in db_connect()
function db_connect() {
return new mysqli(localhost, user, pass, table);
}
function register($username, $email, $password) {
$link = db_connect();
$query = "INSERT INTO proyecto.user (username, password, email)
VALUES ('$username', '$password', '$email')";
$result = mysqli_query($link, $query);
}