Here is my code
$stmt = $mysqli->prepare("SELECT * FROM `accountsToDo` WHERE `OKrname` = ?");
$stmt->bind_param("s", $OKCUsername);
/* execute prepared statement */
$stmt->execute();
if ($stmt->affected_rows > 0){
echo "Exists";
} else {
$stmt = $mysqli->prepare("INSERT INTO `accountsToDo`(`percentageOfMessages`, `RemoveDeletedAccounts`, `RemoveNoReply`, `RemoveNoResponse`, `minMatchPercent`, `minDistance`, `maxDistance`, `blacklistUsernames`, `userEmail`, `OKrname`, `OKword`) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("iiiiiiissss", $percentageOfMessages, $RemoveDeletedAccounts, $RemoveNoReply, $RemoveNoResponse, $minMatchPercent, $minDistance, $maxDistance, $blacklistUsernames, $userEmail, $OKrname, $OKword);
$stmt->execute();
}
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
But now I'm getting the error,
Call to a member function bind_param() on boolean in line 147.
Line 147 is
$stmt->bind_param("iiiiiiissss", $percentageOfMessages, $RemoveDeletedAccounts, $RemoveNoReply, $RemoveNoResponse, $minMatchPercent, $minDistance, $maxDistance, $blacklistUsernames, $userEmail, $OKrname, $OKword);
If all you are doing is inserting into a todo table if the master table doesn't have a matching row, you don't need two statements.
INSERT INTO `accountsToDo`
(`percentageOfMessages`, `RemoveDeletedAccounts`,
`RemoveNoReply`, `RemoveNoResponse`, `minMatchPercent`,
`minDistance`, `maxDistance`, `blacklistUsernames`,
`userEmail`, `OKrname`, `OKword`)
VALUES (?,?,?,?,?,?,?,?,?,?,?)
WHERE NOT EXISTS (SELECT 1 FROM `accountsToDo` WHERE `OKrname` = ?);
Bind your params and you have save a call to the db. This has the advantage that "SELECT 1" acts as a cut operator so it is only evaluated until it finds the first TRUE.
You are missing a space between table name and a list of fields in your $mysqli->prepare
Try this:
$stmt = $mysqli->prepare("INSERT INTO `accountsToDo`
(`percentageOfMessages`,`RemoveDeletedAccounts`,
`RemoveNoReply`, `RemoveNoResponse`,
`minMatchPercent`, `minDistance`,
`maxDistance`, `blacklistUsernames`,
`userEmail`, `OKrname`, `OKword`)
VALUES (?,?,?,?,?,?,?,?,?,?,?)");
According to manual $mysqli->prepare will return FALSE if statement caused an error
UPDATE
Looks like your $mysqli->prepare is expecting 11 variables and you are trying to bind 12
The issue was that I didn't have
$stmt->store_result();
above the first $stmt->execute();
I'm getting:
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't
match number of fields in prepared statement in
E:\XAMPP\htdocs\account\lib\register.php on line 73
When I use this code:
if($stmt = $conn -> prepare("INSERT INTO login(user, pass) VALUES(?, ?)")) {
/* Bind parameters s - string, b - blob, i - int, etc */
$stmt -> bind_param("ss", $user, $pw);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($user, $pw);
/* Close statement */
$stmt -> close();
$userId = $conn->insert_id;
}
I can't understand, why this happens every time, what is wrong in my code snippet?
You are attempting to bind_result on a statement that is not returning any results.
Remove this line.
$stmt -> bind_result($user, $pw);
A lot has changed in the PHP world since the last time I was using it (few years back). Now it seems I need to learn again everything, which takes me to my current problem.
/* Create a prepared statement */
$stmt1 = $mysqli -> prepare("SELECT channel FROM channel WHERE barcode=?");
$stmt2 = $mysqli -> prepare("SELECT action FROM action WHERE barcode=?");
$stmt3 = $mysqli -> prepare("SELECT reason FROM reason WHERE barcode=?");
$stmt4 = $mysqli -> prepare("SELECT supplier_name FROM suppliers WHERE barcode=?");
/* Bind parameters */
$stmt1 -> bind_param("s", $_POST['channel']);
$stmt2 -> bind_param("s", $_POST['action']);
$stmt3 -> bind_param("s", $_POST['reason']);
$stmt4 -> bind_param("s", $_POST['supplier']);
/* Execute it */
$stmt1 -> execute();
$stmt2 -> execute();
$stmt3 -> execute();
$stmt4 -> execute();
/* Bind results */
$stmt1 -> bind_result($channel1);
$stmt2 -> bind_result($action1);
$stmt3 -> bind_result($reason1);
$stmt4 -> bind_result($supplier1);
/* Fetch the value */
$stmt1 -> fetch();
$stmt2 -> fetch();
$stmt3 -> fetch();
$stmt4 -> fetch();
echo "Channel ".$channel1."; Action: ".$action1."; Reason: ".$reason1."; Supplier: ".$supplier1;
Eeverything works just fine one by one, but when it's all combined... nothing. Only the first statement will work. What am I doing wrong???
This happen because:
mysqli_stmt::execute:
Note:
When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must be used to fetch the data prior to performing any additional queries.
mysqli_stmt::close:
Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.
The binding (for params and results) can be done before execution... just excludes execute(), fetch() and close() for each statment in one separate block each.
Also take in mind the use of trigger_error($mysqli->error); to check possible errors while using prepare().
I apologise if the title is poor.
I have been researching Prepared Statements and found the following code here:
/* Create a new mysqli object with database connection parameters */
$mysqli = new mysqli('localhost', 'username', 'password', 'db');
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("SELECT priv FROM testUsers WHERE username=?
AND password=?")) {
/* Bind parameters
s - string, b - blob, i - int, etc */
$stmt -> bind_param("ss", $user, $pass);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
echo $user . "'s level of priviledges is " . $result;
/* Close statement */
$stmt -> close();
}
/* Close connection */
$mysqli -> close();
The part that I don't understand, is how in the SQL Query "SELECT priv FROM testUsers WHERE username=?
AND password=?"), the system knows what the username and password is. I know that the ? marks are placeholders, and below is also confusing me a bit:
$stmt -> bind_param("ss", $user, $pass);
Because I do not see how the $user and $pass have been defined at any point, and thus how the SQL query will substitute the $user and $pass for an actual string. If that makes sense. Where have these values come from? Where are they in this example?
That's because they aren't. This is probably just an example how to use the script. You will have to define the $user and $pass variables by yourself, for example from an $_POST variable of some sort.
The bind_param function handles the arguments. You have to add the same amount of arguments to the query as you put question marks in it. Than the parser in the core of MySQLi can add the arguments safely to the query.
They are being matched by order. Same logic in string building ("{0} is greater than {1}", "5", "3") becomes 5 is greater than 3. So with parameters
$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);
they are all ordered and matches with columns.
If the original script writer had register_globals ON, e.g. in a previous version of PHP, then the user and pass were passed in from the form in the same way as $_POST['user'] and $_POST['pass']. I offer that you can replace them now and move on.
I'm learning MySQLi in php and I can't understand why I am getting an Call to a member function prepare() on a non-object error.
Here's my code as below:
public function fetch_posts($num = 5)
{
global $mysqli;
if($stmt = $mysqli->prepare("SELECT * FROM posts ORDER BY id desc LIMIT ?"))
{
/* Bind parameters
s - string, b - boolean, i - int, etc */
$stmt -> bind_param("i", $num);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
/* Close statement */
$stmt -> close();
}
$mysqli -> close();
}
$mysqli is the MySQLi connection call, $mysqli = new mysqli(DB_HOST, DB_ID, DB_PW, DB); which resides in the __construct() function, both which are within the same class.
Have I done something obviously wrong here? I can't see it.
$mysqli is not the MySQL connection for some reason.
If you don't have a debugger configured so you can step through the code, use gettype($mysqli) right before your prepare() call to see what it is you're dealing with.