Reputation: 1391
My header is probably ambiguous so i'm gonna explain it.
I have a table "books" in my database. I need to retrieve the table using php and then choose the book and comment about the book.
I got the retrieving part, a table with all my books is displayed.
I am stuck with selecting the book part.
Here is what i need to do:
I just need help with selecting the book from the table. How to do it?
Upvotes: 0
Views: 133
Reputation: 2382
let me assume you have a these rows in the table book book_id(PI), name author
<form method="post" action="something.php">
<select name="book">
<?php
$stmt = $mysqli->prepare("SELECT id,name,author FROM books");
if($stmt) {
$stmt->execute();
$result = $stmt->get_result();
while ($myrow = $result->fetch_assoc()) {
echo '<option value='.$myrow['book_id'].'>'.$name.' '.$author.'</option>';
}
//instead of $result you can also do
if($stmt) {
$stmt->execute();
$stmt->bind_result($id,$name,$author):
while ($stmt->fetch()) {
echo '<option...
}
?>
if you want both the id and name or all of the three go to this link
if you want to select your books on certain criteria, for example lets say author=enid
then modify the query like this:
$stmt = $mysqli->prepare("SELECT id,name,author FROM books WHERE author=?");
if($stmt) {
$stmt->bind_param("s",$input_name);
$stmt->execute();
.....
then at the something.php use the $_POST[''] to get the user inputs. then u can make a form use a hidden value with a value= id of the book make a comment box use a submit button. then in another table 'comments' u can have two rows comment_id(PI) book_id and comment
then use the insert query
$stmt=mysqli_prepare("insert into comments (book_id,comment) values (?,?)");
if($stmt) {
$stmt->bind_param('is',$book_id,$comment);
$stmt->execute();
}
always remember to use $stmt->close() and $stmt->free() . how to do that will be answred by php.net
Upvotes: 1