Binding parameters in mysql - php

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

Related

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

What is the query binding marker for CURRENT_DATE when using mysqli prepared statements?

So I've finished building a question and answer site and am now trying to defend it against SQL injection but having problems with CURRENT_DATE. I want to insert current date with the question into db but what binding marker would that be? "s" for string is not working?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "questions87";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
session_start();
$question = $_POST["question"];
$uname = $_SESSION['username'];
$qa_email =$_SESSION['email'];
// prepare and bind
$stmt = $conn->prepare("INSERT INTO login (username, username, q_date, qa_email) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $question, $uname, CURRENT_DATE, $qa_email);
$stmt->execute();
if ($stmt) {echo "Thank you ". $uname . " Your question has been submitted " . "<br>";}
else {echo "Error: " . $sql . "<br>" . mysqli_error($conn);}
$stmt->close();
$conn->close();
?>
Use simple mysql function NOW() and remove placeholder for q_date:
$stmt = $conn->prepare("INSERT INTO login (username, username, q_date, qa_email) VALUES (?, ?, NOW(), ?)");
$stmt->bind_param("sss", $question, $uname, $qa_email);
Btw, I noticed, you have field username twice in this query. I suppose one of the occurences should be replaced with some other field.

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

Get query back from MYSQLi prepared statement

My prepared statement looks like this:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// prepare and bind
$stmt = $conn->prepare("INSERT INTO `devices` (`deviceName`, `type`, `deviceToken`) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $deviceName, $deviceToken, $type);
$stmt->execute();
echo "executed";
$result = $stmt->get_result();
$conn->close();
And I want to echo the query.
I know the PDO method:
$binded_query = $stmt->queryString
But I need to use MYSQLi. So how can I do that?
$sql = "INSERT INTO `devices` (`deviceName`, `type`, `deviceToken`) VALUES (?, ?, ?)"
$stmt = $conn->prepare($sql);
echo $sql; // here you go

how can fix the error Call to a member function bind_param() on a non-object in Can"t Insert in to database

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

Categories