Should I manually check for errors when calling mysqli_stmt_prepare?
Is there a good reason to manually check the return value of that
function as it is shown in the manual?
Nope, there isn't.
Mysqli can check for errors automatically, you just have to ask it to do so.
Configure mysqli to throw an exception every time it gets an error, and you won't have to check any mysqli function for the error manually anymore!
Hence, add the following line before mysqli_connect()
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and that's all!
Note that you have to deal with possible errors the right way. You can read about it in my article, PHP error reporting
How can I add error handling to my SQL UPDATE function in PHP?
mysqli_stmt_affected_rows()
will tell you how many rows were updated.
<?php
function updateUid($conn, $usersUid, $rowId) {
$sql = "UPDATE users SET usersUid = ? WHERE usersId = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
//error - bad SQL call
exit();
}
mysqli_stmt_bind_param($stmt, "ss", $usersUid, $rowId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_affected_rows($stmt) > 0;
mysqli_stmt_close($stmt);
return $result;
}
Note that this can be 0 for two reasons:
- No rows match
$rowId
- The
usersUid
in the matching row is already equal to$usersUid
, so nothing changed.
See PHP, MySQL - can you distinguish between rows matched and rows affected? for how you can change the way you connect to the DB so that this returns the number of rows that were matched by the WHERE
condition instead of the rows that were actually updated.
Something wrong with mysqli statement prepare
You are using an undefined variable in your sql statement. In your binding you refer to $username
but in your variable definition you define $user_name
.
// wrong code
$user_name = $_POST['name'];
mysqli_stmt_bind_param($statement, "s", $username);
// fixed code
$user_name = $_POST['name'];
mysqli_stmt_bind_param($statement, "s", $user_name);
Try changing the statement/variable to match your declaration.
mysqli_stmt object is not fully initialized error message
If we remove your if/else check and run everything, with the mysqli_stmt_prepare
after the mysqli_stmt_init
we get what we expect.
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
So the logic on your if
seems like it needs a ! (meaning false). Try this alteration to your code block:
$sql = 'INSERT INTO user_table (user_name, user_email, user_password) VALUES (?, ?, ?)';
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("location: ../signup.php?error=sqlerror");
exit();
} else {
//hashing password
$hashedPass = password_hash($password, PASSWORD_DEFAULT);
//inserting hashed password.
mysqli_stmt_bind_param($stmt, 'sss', $username, $email, $hashedPass);
mysqli_stmt_execute($stmt);
header("location: ../signup.php?success=registered");
exit();
}
The above code worked in my test.
How to redirect PHP page on MySQL database connection failure
OK,
This is what I was looking for and is working for me mow
try{
$conn = new mysqli($servername, $username, $password, $dbname);
}
catch(Exception $e){
header('Location: 500.php');
die();
}
PHP error with prepared statements using OOP
This code is wrong on so many levels (as you would expect from a youtube tutorial), but the main problem is that the method showDeleteArticle() is wrong and misleading.
There is no reason for this method to be at all. Which is proven by the fact the other answer is accepted. The offered code always returns a true-like value, hence the condition inside showDeleteArticle() becomes useless. One could rewrite it as
public function showDeleteArticle($id) {
echo "Article has successfully been deleted.";
}
as it will never enter the else part anyway.
Let alone any Controller should never blurt out any data directly, not through View. Least after a POST request after which there must be a redirect, not output.
How to execute sql code based on fetch array
It's not clear what your Insert logic is and what exactly you want to insert but let me give you how I would structure such a query (including some safeguards such as prepared statements) and hopefully you can just change the SQL statements based on what you need. I have left comments on most rows to explain
<?php
include 'includes/conn.php';
include 'includes/scripts.php';
if (isset($_POST['no'])) {
$sca=trim($_POST['no'],"");
$credentials="";
$sql = "SELECT * FROM `barcode`";
$mysqli = new $conn;
// Prepare the statement
$stmt = $mysqli->prepare($sql);
// Attempt to execute
if ($stmt->execute()) {
// Save result
$result = $stmt->get_result();
// save the result in an assoc array
$row = $result->fetch_all(MYSQL_ASSOC);
// If there is a returned entry
if (count($row) > 0) {
if ($row['credentials'] === $sca) {
// close the statement so we can re-use
$stmt->close();
// We assume id is what we need
$id = $row['id'];
// Now you have to fix your INSERT statement here. I am not sure what you need to insert but follow the general docs on how to insert https://www.php.net/manual/en/mysqli-stmt.bind-param.php
$stmt = $mysqli->prepare("INSERT IGNORE INTO `voters` (columnName) VALUES (?)");
// Here you need to decide what you are inserting and change the variable
$stmt->bind_param("s", $whatever_variable_you_insert);
// Attempt to execute
if ($stmt->execute()) {
// if successful, proceed with the deletion too... or you can put it outside this execute condition
$stmt->close();
// Prepare the delete statement
$stmt = $mysqli->prepare("DELETE FROM `barcode` WHERE id=?");
// Bind the param
$stmt->bind_para("s", $id);
if ($stmt->exceute()) {
// something else or as you wanted - refresh
header("refresh: .5");
}
}
}
}
}
}
?>
Related Topics
Convert from MySQL Datetime to Another Format With PHP
PHP Syntax For Dereferencing Function Result
Download File to Server from Url
Increasing the Maximum Post Size
Call to a Member Function Bind_Param() on a Non-Object
How to Call a Function from a String Stored in a Variable
How to Flush Output After Each 'Echo' Call
How to Convert an Object to an Array
Laravel Csrf Token Mismatch For Ajax Post Request
Fatal Error: Call to a Member Function Fetch_Assoc() on a Non-Object
PHP - Concatenate or Directly Insert Variables in String
PHP Display Image Blob from MySQL
PHP: How to Send Http Response Code
How to Create Custom Helper Functions in Laravel
Detecting Request Type in PHP (Get, Post, Put or Delete)
Invoking a PHP Script from a MySQL Trigger