I am new to using prepared statement with PHP. I am trying to get the value of "full_name"... So far I am stuck over here. Can anyone please help figure this out? Thanks!
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT * FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$row = $stmnt->fetch();
You need to use bind_result to bind variables to the columns you want. Then each time you call fetch(), those variables will be updated with the next row's values. fetch() with mysqli does not return you the row/result.
This means you cannot use SELECT *. You need to specify which fields you want.
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT full_name FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$stmnt->bind_result($full_name);
$stmnt->fetch();
echo $full_name;
Or, if you have the mysqlnd driver installed, you can use get_result() to get a result set just like if you had ran a normal query, not a prepared statement.
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT * FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$result = $stmnt->get_result();
$row = $result->fetch_assoc();
echo $row['full_name'];
Related
I tried to update a row in table showtable
Bugupdate
By using the php code below, binding a bugID to a SQL UPDATE statement to update the row I want to but it doesn't seem to work, is it the problem lie in my SQL statement ?
$id = $_GET['update'];
$games = htmlentities($_POST['games']);
$version = htmlentities($_POST['version']);
$platform = htmlentities($_POST['platform']);
$frequency = htmlentities($_POST['frequency']);
$proposal = htmlentities($_POST['proposal']);
$SQLstring2 = "UPDATE " .$TableName. " SET Game=?,Version=?,Platform=?,Frequency=?,Proposed solution=? WHERE BugID= " .$id;
if ($stmt = mysqli_prepare($DBconnect, $SQLstring2)) {
mysqli_stmt_bind_param($stmt,'sssss', $games, $version, $platform, $frequency, $proposal);
$QueryResult2 = mysqli_stmt_execute($stmt);
if ($QueryResult2 === FALSE) {
echo "<p>Unable to execute the query.</p>"
. "<p>Error code "
. mysqli_errno($DBconnect)
. ": "
. mysqli_error($DBconnect)
. "</p>";
} else {
echo "<h1> Thank you for your contribution";
}
mysqli_stmt_close($stmt);
}
mysqli_close($DBconnect);
Try to rename Proposed solution column to Proposed_solution and adapte the sql query like this :
$SQLstring2 = "UPDATE " .$TableName. " SET Game=?,Version=?, Platform=?, Frequency=?, Proposed_solution=? WHERE BugID= " .$id;
my problem is that I want to loop through an array and insert every entry of that array into another column of an mySQL table. To be honest, I'm not sure if that's the best way to design my database, but that's one way I could imagine, it works. If someone has a better idea of how to do it or a link for best practice or something, that would be awesome.
So what I want to do: I have a form where someone can register to offer a food delivery service. He can enter name etc. and up to 10 offers (limitation of the database table). These information should be insert into the table 'anbieter' into the fields 'angebot_0' , 'angebot_1' ...
So what I did is:
if (isset($_POST['register_offer']) and isset($_POST['anbieter-email'])){
$name = $loc = $cat = $email = $password ="";
$angebot = array();
// fill all variables
$name = test_sql($_POST['anbieter-name']);
$email = test_sql($_POST['anbieter-email']);
$password = test_sql($_POST['anbieter-password']);
$loc = test_sql($_POST['anbieter-loc']);
$cat = test_sql($_POST['anbieter-cat']);
// fill $angebot with all given angebot[] entries
foreach($_POST['angebot'] as $ang) {
$angebot[] = test_sql($ang);
}
if(!empty($name) and !empty($loc) and !empty($email) ){
/* decrypt password */
$password = password_hash($password, PASSWORD_BCRYPT, ["cost" => 12]);
// insert name, email, password, location and category into database
/* Prepared statement, stage 1: prepare */
if (!($stmt = $conn->prepare("INSERT INTO anbieter (anbieter_name, anbieter_email, anbieter_password, anbieter_loc, anbieter_cat) VALUES (?, ?, ?, ?, ?)"))) {
echo "Prepare failed: (" . $stmt->errno . ") " . $stmt->error;
}
/* Prepared statement, stage 2: bind and execute */
if (!$stmt->bind_param('sssss', $name, $email, $password, $loc, $cat)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$userid = $stmt->insert_id;
// safe all angebot[] entries to database - angebot[0]-> angebot_0
for($x=0; $x < count($angebot) ; $x++) {
$upd = $conn->prepare("UPDATE anbieter SET angebot_".$x." = ? WHERE abieter_ID = ? ");
$upd->bind_param('si', $angebot[$x], $userid);
$upd->execute();
}
So when I do this, I get the error:
Fatal error: Call to a member function bind_param() on boolean in ...
It's a super bad way to do that by using $x to name different fields of the table, but that's the only way I could think of it works :/
I hope someone can help me here! :)
Thanks a lot!
My suggestion instead on single record update query multiple times you can do it in a single query,
Eg:
$query = "UPDATE anbieter SET";
for ($x = 0; $x < count($angebot); $x++) {
$query .= " angebot_" . $x . " = '" . $angebot[$x] . "', ";
}
echo $query .= " WHERE abieter_ID = " . $userid;
So thanks for you help, but it didn't help much :/
After trying some other possibilties, I solved it like:
$x = 0;
foreach($angebot as $offer){
if (!($upd = $conn->prepare("UPDATE anbieter SET angebot_".$x." = '". $offer. "' WHERE anbieter_ID = " . $userid))) {
echo "Prepare failed: (" . $upd->errno . ") " . $upd->error;
}
/* Prepared statement, stage 2: bind and execute */
if (!$upd->execute()) {
echo "Execute failed: (" . $upd->errno . ") " . $upd->error;
}
$x = $x+1;
}
Maybe it will help someone else :)
This is odd and I just can't seem to find what is wrong.
Here is a simple example:
In my PHP code, I can select from a table and have results returned.
But, If I change my SQL statement to select from a view, no results are returned.
This Code Returns results:
$link = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
$sql_stmt_bind = "Select fk_member_id as ID FROM member_role LIMIT 1";
$stmt = $link->stmt_init();
$stmt->prepare($sql_stmt_bind);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($mem_id);
$stmt->fetch();
echo '<br>';
echo 'rows: ' . $stmt->num_rows;
echo '<br>';
//echo 'lastname: ' . $lastname;
echo 'ID: ' . $mem_id;
echo '<br>';
The Results:
rows: 1
ID: 1
This Code Returns unexpected results:
$link = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
$sql_stmt_bind = "Select fk_member_id as ID FROM vw_test LIMIT 1";
$stmt = $link->stmt_init();
$stmt->prepare($sql_stmt_bind);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($mem_id);
$stmt->fetch();
echo '<br>';
echo 'rows: ' . $stmt->num_rows;
echo '<br>';
//echo 'lastname: ' . $lastname;
echo 'ID: ' . $mem_id;
echo '<br>';
The Results:
rows: 0
ID: 0
This is the Create statement for the View:
Create or replace View vw_test
as
Select fk_member_id FROM member_role
;
So I'm at a total loss.
I've been running the same code for the past 4 or 5 years with no issues.
(This is for a community sports association and runs for only a few months of the year.)
I was double checking the code before I turned on the web pages again...and now all of my code accessing views no longer works.
Please help! thanks.
UPDATE
I'm now using this code segment:
$stmt = $link->stmt_init();
$pre = $stmt->prepare($sql_stmt_bind);
if ( false===$pre ) {
die('prepare() failed: ' . htmlspecialchars($stmt->error));
}
$exe = $stmt->execute();
if ( false===$exe ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->store_result();
$bind_r = $stmt->bind_result($mem_id);
if ( false===$bind_r ) {
die('bind_result() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->fetch();
The error I now receive is:
execute() failed: Prepared statement needs to be re-prepared
Any Ideas? Thanks.
Try to check your code to know where the problem is.
Try this:
$link = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
$sql_stmt_bind = "Select fk_member_id as ID FROM vw_test LIMIT 1";
$stmt = $link->stmt_init();
$pre = $stmt->prepare($sql_stmt_bind);
if ( false===$pre ) {
die('prepare() failed: ' . htmlspecialchars($stmt->error));
}
$exe = $stmt->execute();
if ( false===$exe ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->store_result();
$bind_r = $stmt->bind_result($mem_id);
if ( false===$bind_r ) {
die('bind_result() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->fetch();
echo '<br>';
echo 'rows: ' . $stmt->num_rows;
echo '<br>';
//echo 'lastname: ' . $lastname;
echo 'ID: ' . $mem_id;
echo '<br>';
EDIT
Work around for the problem(failed: Prepared statement needs to be re-prepared)
- using the PDO adapter instead of Mysql adapter
- Add this Attribute to your connection string $link->setAttribute( PDO::ATTR_EMULATE_PREPARES, true);
This question already has answers here:
Using fetch_assoc on prepared statements
(3 answers)
Closed last year.
I am able to get the result from a standard SQL query however when it comes to prepared statements I am fine up until it comes to getting the result from the query.
As background the query will result with more than one row.
$sql = "SELECT * FROM blog WHERE ID=?";
if (!$stmt = $con -> prepare($sql)) {
echo "Prepare failed: (" . $con->errno . ") " . $con->error;
}
if (!$stmt->bind_param("i", $_GET["ID"])) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
while($row = $stmt->fetch_assoc()){
$blog_title = $row['title'];
$blog_body = $row['body'];
$blog_blurb = $row['blurb'];
$blog_date = $row['posted'];
$blog_tags = $row['tags'];
}
This results in
Fatal error: Call to undefined method mysqli_stmt::fetch_assoc()
However, I have tried what was outlined in the PHP manual but have not succeeded.
Here is better way to do it.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mydatabase = new mysqli('localhost', 'root', '', 'database');
$id = $_GET['id'];
$stmt = $mydatabase->prepare("SELECT * FROM `blog` where ID = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result(); //get the results
while ($row = $result->fetch_assoc()) {
echo $row['whatever']; //do whatever here
}
If get_result() doesn't exist in your installation, use this:
$stmt->bind_result($column1, $column2);
while ($stmt->fetch()) {
echo $column1;
echo $column2;
}
My num_rows is coming back as 0, and I've tried calling it several ways, but I'm stuck. Here is my code:
$conn = new mysqli($dbserver, "dbuser", "dbpass", $dbname);
// get the data
$sql = 'SELECT AT.activityName, AT.createdOn
FROM userActivity UA, users U, activityType AT
WHERE U.userId = UA.userId
and AT.activityType = UA.activityType
and U.username = ?
order by AT.createdOn';
$stmt = $conn->stmt_init();
$stmt->prepare($sql);
$stmt->bind_param('s', $requestedUsername);
$stmt->bind_result($activityName, $createdOn);
$stmt->execute();
// display the data
$numrows = $stmt->num_rows;
$result=array("user activity report for: " . $requestedUsername . " with " . $numrows . " rows:");
$result[]="Created On --- Activity Name";
while ($stmt->fetch())
{
$msg = " " . $createdOn . " --- " . $activityName . " ";
$result[] = $msg;
}
$stmt->close();
There are multiple rows found, and the fetch loop process them just fine. Any suggestions on what will enable me to get the number of rows returned in the query?
Suggestions are much appreciated. Thanks in advance.
You need to call $stmt->store_result() first, just before $stmt->num_rows.
Try to add this before you call num_rows;.
$stmt->store_result();
$stmt->store_result();
$numrows = $stmt->num_rows;
Check this: http://php.net/manual/en/mysqli-result.num-rows.php and this
http://php.net/manual/en/mysqli-stmt.num-rows.php
I don't know if this will fix it, but you can't bind_results until after you execute the query, if I'm not mistaken.
Also your while loop:
while ($stmt->fetch())
{
$msg = " " . $createdOn . " --- " . $activityName . " ";
$result[] = $msg;
}
you will lose all of the $msg variables with each iteration of the loop, except the last setting because you either need to do $msg .= or make $msg an array $msg[] =