php prepared statements insert not working - php

I have researched it a lot online and spent a lot of time trying to fix this problem.
My code
function createNewAccount() {
global $response;
global $conn;
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
}
the error I get is
Warning: mysqli::prepare(): Couldn't fetch mysqli in
C:\xampp\htdocs\authentication\register.php on line 105
Fatal error: Uncaught Error: Call to a member function bind_param() on
null in C:\xampp\htdocs\authentication\register.php:106 Stack trace:
#0 C:\xampp\htdocs\authentication\register.php(139): createNewAccount() #1 {main} thrown in
C:\xampp\htdocs\authentication\register.php on line 106
I cant seem to find any solution. Any help is highly appreciated.

PHP Variables need to be set before using them:
function createNewAccount() {
global $response; // If you dont need this remove it
global $conn;
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
$stmt->execute();
}

Related

My error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

I got the problem in my blog. When I use single quote in textik this error appear.
INSERT INTO clanky (nadpis, textik, datum, autor, kategorie) VALUES (?, ?, ?, ?, ?);
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?, ?, ?)' at line 2
I already know that you cant use single quotes in string due to SQL injection. So im trying to fix it. I tried so many tutorials but nothing helped me.
<?php
if (isset($_POST["btn"])) {
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("ERROR: Could not connect. " . $conn->connect_error);
}
$nadpis = mysqli_real_escape_string($conn, $_POST['nadpis']);
$textik = mysqli_real_escape_string($conn, $_POST['textik']);
$datum = mysqli_real_escape_string($conn, $_POST['datum']);
$autor = mysqli_real_escape_string($conn, $_POST['autor']);
$kategorie = mysqli_real_escape_string($conn, $_POST['kategorie']);
$sql = "INSERT INTO `clanky` (`nadpis`, `textik`, `datum`, `autor`, `kategorie`)
VALUES (?, ?, ?, ?, ?);";
// '". $_POST['nadpis']."','". $_POST['textik']."','". $_POST['datum']."','". $_POST['autor']."','". $_POST['kategorie']."'
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt, "ssiss", $nadpis, $textik, $datum, $autor, $kategorie);
mysqli_stmt_execute($stmt);
}
if (mysqli_query($conn, $sql)) {
echo "New Record added";
header("Location: https://www.globalgraphicdesign.eu/welcome.php");
}else {
echo "Error" . $sql . "" . mysqli_error($conn);
}
$conn->close();
}
?>
I should redirect you to welcome page.
You're trying to prepare it, and using query(), thereby attempting to execute it twice. It will fail when using query(), because placeholders ? are not allowed there. You should also not escape input when using a prepared statement. You should also not output anything before a header() call. You can also enable MySQLi to throw exceptions, which makes error-handling much easier.
Your entire snippet can be reduced to the following.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$conn = new mysqli($servername, $username, $password, $dbname);
if (isset($_POST["btn"])) {
$sql = "INSERT INTO `clanky` (`nadpis`, `textik`, `datum`, `autor`, `kategorie`)
VALUES (?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssss", $_POST['nadpis'], $_POST['textik'], $_POST['datum'], $_POST['autor'], $_POST['kategorie']);
$stmt->execute();
header("Location: https://www.globalgraphicdesign.eu/welcome.php");
$stmt->close();
exit;
}
} catch (Exception $e) {
echo "Something went wrong. Please try again later";
error_log($e->getMessage());
}

Call to a member function bind_param() on a non-object on line 26 [duplicate]

This question already has answers here:
Call to a member function prepare() on a non-object PHP Help [duplicate]
(8 answers)
Closed 5 years ago.
I can't figure out why I keep getting this error: Call to a member function bind_param() on a non-object on line 26
Can someone help me? I don't use PHP often.
<?php
$guests = $_POST['guests'];
$organizations = $_POST['organizations'];
$email = $_POST['email'];
$team = $_POST['team'];
if (trim($email) == "") {
include("blank_email.php");
exit(0);
}
$mysqli = new mysqli("localhost", "username", "******", "signin_database");
function error_page($title, $description, $errmsg) {
include("error.php");
}
function thankyou($email) {
include("thankyou.php");
}
if ($mysqli->connect_errno) {
error_page("Cannot Connect", "Cannot connect to database", $mysqli->connect_error);
}
else {
$stmt = $mysqli->prepare("INSERT INTO user_input (guests, organizations, email, team, timestamp) VALUES (?, ?, ?, ?, NOW());");
$stmt->bind_param("isss", $guests, $organizations, $email, $team);
if (!$stmt->execute()) {
error_page("Could not Add", "Could not add email and comment", $stmt->error);
}
else {
thankyou($email);
}
$stmt->close();
$mysqli->close();
}
?>
First, $mysqli->connect_errno needs to be $mysqli->connect_errno() and $mysqli->connect_error needs to be $mysqli->connect_error().
Then, you should change$mysqli->prepare to:
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("INSERT INTO user_input (guests, organizations, email, team, timestamp) VALUES (?, ?, ?, ?, NOW())")) {
//bind param, execute, etc.
} else {
//handle the error
}

mysql row id is returning 0 when it should be returning a higher number

thanks for taking the time to read this and i apologize in advance for how messed up my coding is, i'm trying to teach myself. i am running into an error when it comes to getting the id of the row when the check is run if the name, email or telephone of the input matches the db. i'm trying to get the id so that i can tie that id as the "owner_id" of the message when i store it.
Fatal error: Call to undefined method mysqli_stmt::fetch_assoc() in /var/www/a-website.com/html/inc/db3.php on line 35
line 35 is
while($row = $prepared_check->fetch_assoc()){
here is the whole php file. its required_once in another php file, and run in that php file using
checkRecords($name, $tel2, $email);
anyways, onto the php file.
$run_check = 1;
function newInsert($name, $email, $tel, $mysqli){
$prepared_insert = $mysqli->prepare("INSERT INTO call_list (name, email, tel) VALUES (?, ?, ?)");
$prepared_insert->bind_param('sss', $name, $email, $tel);
$prepared_insert->execute();
$run_check = 1;
}
function storeMessage($id, $message, $mysqli){
$prepared_message = $mysqli->prepare("INSERT INTO messages (owner_id, message) VALUES (?, ?)");
$prepared_message->bind_param('ss', $id, $message );
$prepared_message->execute();
$prepared_message->close();
$run_check = 0;
}
function checkRecords($name, $email, $tel, $message){
$servername = "localhost";
$username = "a_valid_user";
$password = "some_valid_password";
$dbname = "call_list";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if($mysqli->connect_errno){
$_SESSION['result_sql'] = "<div class='alert alert-danger'>Failed to connect to MySQL:(".$mysqli->errno.")". $mysqli->error."</div>";
}
$prepared_check = $mysqli->prepare("SELECT * FROM call_list WHERE name = ? OR tel = ? OR email = ?");
$prepared_check->bind_param('sss', $name, $tel, $email);
$prepared_check->execute();
$prepared_check->store_result();
$nm_rows = $prepared_check->num_rows;
$prepared_check->bind_result($id, $name, $tel, $email);
while($row = $prepared_check->fetch_assoc()){
echo "grabbed ". $nm_rows ." results<br><br>";
if($nm_rows === 0){
echo "trying to insert<br><br>". $name ."<br><br>". $email ."<br><br>". $tel;
newInsert($name, $email, $tel2, $mysqli);
}else{
echo "i'm trying to store a message with the owner id of ". $row['id'] ." who should be".$row['name'];
echo "<br><br> here's the message: <br><br>". $message ."<br><br><br>";
storeMessage($id, $message, $mysqli);
}
}
}
A mysqli statement don't have fetch_assoc() method. Instead, you may just use: fetch()

Having an error with executing my query

Well, I'm creating a registration system for my website but I'm having trouble executing my query. I've tried to troubleshoot the problem, but I've had no success. Kind of confused :(
Here is my code:
public function registerUser($username, $password, $email) {
global $core;
if(empty($username) || empty($password) || empty($email)) {
throw new Exception ('A required field was left blank');
} else {
//SQL Query Data
$data['username'] = $username;
$data['password'] = $core->encrypt($password);
$data['email'] = $email;
$data['userKey'] = rand(999999, 100000);
$data['ip'] = $_SERVER['REMOTE_ADDR'];
$data['date'] = time();
//SQL Query
$sql = "INSERT INTO `u_userdata` ('user-key', 'username', 'password', 'email', 'register-ip', 'register-date') VALUES (:userKey, :username, :password, :email, :ip, :date)";
$STH = $this->DBH->query($sql);
$STH->execute($data);
}
}
and here is the error I'm getting:
Fatal error: Call to a member function execute() on a non-object in C:\xampp\htdocs\community\inc\user.inc.php on line 33
I'm guessing it's an error with the query, but I'm not sure what!
I think you have got PDO::prepare() mixed up with PDO::query():
It should be either:
$result = $this->DBH->query($sql);
Or:
$STH = $this->DBH->prepare($sql);
$STH->execute($data);
From the docs:
PDO::query() executes an SQL statement in a single function call,
returning the result set (if any) returned by the statement as a
PDOStatement object.
You would normally use PDO::prepare() if you are going to issue the same statement repeatedly, or if you need to bind parameters. As far as I am aware, it is not possible to bind parameters to your query prior to using PDO::query().
Note that with PDO::prepare() you can either use PDOStatement::bindParam() to bind parameters prior to calling PDOStatement->execute(), or you can pass the parameters as an array to PDOStatement->execute().
You also need to prefix your array keys with a colon. So the final result would be:
$data[':username'] = $username;
$data[':password'] = $core->encrypt($password);
$data[':email'] = $email;
$data[':userKey'] = rand(999999, 100000);
$data[':ip'] = $_SERVER['REMOTE_ADDR'];
data[':date'] = time();
//SQL Query
$sql = "INSERT INTO `u_userdata` ('user-key', 'username', 'password', 'email', 'register-ip', 'register-date') VALUES (:userKey, :username, :password, :email, :ip, :date)";
$STH = $this->DBH->prepare($sql);
$STH->execute($data);
You should use ` quote instead of ' in insert query.
"INSERT INTO u_userdata (user-key, username, password, email, register-ip, register-date) VALUES (:userKey, :username, :password, :email, :ip, :date)
the query() function executes the sql statement. you should use the prepare() function.
i'm assuming that you are using pdo, because of the pdo tag
$data[':username'] = $username;
$data[':password'] = $core->encrypt($password);
$data[':email'] = $email;
$data[':userKey'] = rand(999999, 100000);
$data[':ip'] = $_SERVER['REMOTE_ADDR'];
$data[':date'] = time();
//SQL Query
$sql = "INSERT INTO `u_userdata` ('user-key', 'username', 'password', 'email', 'register-ip', 'register-date') VALUES (:userKey, :username, :password, :email, :ip, :date)";
$stmt = $this->DBH->prepare($sql);
$stmt->execute($data);

what is wrong with this code

class MyClass {
private $db;
// Constructor
function __construct() {
$this->db = new mysqli('localhost', 'root', 'root', 'Test_db');
$this->db->autocommit(FALSE);
}
// Destructor
function __destruct() {
$this->db->close();
}
// Main method
function MyFun() {
// Check for required parameters
if (isset($_POST["name"]) && isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["email"])) {
echo "Before \n";
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$activation = 0;
echo "After \n";
// tracking
$stmt = $this->db->prepare("INSERT INTO users (name, username, password, email,activation) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("is", $name, $username, $password, $email, $activation); //Line 95
$stmt->execute();
$stmt->close();
}
Output:
Before
After
Invalid request
MAMP Console:
[15-Apr-2011 15:09:10] PHP Warning: mysqli_stmt::bind_param() [<a href='function.mysqli-stmt-bind-param'>function.mysqli-stmt-bind-param</a>]: Number of elements in type definition string doesn't match number of bind variables in /Applications/MAMP/htdocs/Test/reg.php on line 95
The number is the same but I don't know why this error appears
$stmt->bind_param("is", $name, $username, $password, $email, $activation);
Your "definition" string ("is") contains only two definitions, integer and string ... you should have 5 in there.
$stmt->bind_param("sssss", $name, $username, $password, $email, $activation);
... for example ...
You are only having five ? placeholders in your query, yet you're trying to bing six values to the query.
$stmt->bind_param("is", $name, $username, $password, $email, $activation);
"is"
$name
$username
$password
$email
$activation
The format you are giving does only contain 2 definition, yet it must contain 5 to match your query. Try "sssss".
The "is" is the sixth variable, I suggest you remove this or add the field name in the statement:
$stmt->bind_param("is", $name, $username, $password, $email, $activation);
Either remove from bind_param:
$stmt = $this->db->prepare("INSERT INTO users (name, username, password, email,activation) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param($name, $username, $password, $email, $activation);
or add to field names:
$stmt = $this->db->prepare("INSERT INTO users (**is**, name, username, password, email,activation) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("**is**", $name, $username, $password, $email, $activation);
or
$stmt = $this->db->prepare("INSERT INTO users (name, username, password,
email,activation) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("issss", $name, $username, $password, $email, $activation);

Categories