Create basic php page not working - php

I'm trying to create new page in PHP(new_page.php), successful created page will be insert into database (create_page.php), but now it is not working, not sure which steps i am missing, any helps are appreciate. Below is my code & screenshots:
Mysql table:
http://i60.tinypic.com/2h3aofr.png
new_page.php
http://i60.tinypic.com/21dmop2.png
<?php $host = "localhost";
$name = "root";
$password = "";
$db = "test_son";
$connection = mysqli_connect($host, $name, $password, $db);
//Check if connect to MySQL works
if (mysqli_connect_errno()){
die("Connection to MySql error " . mysqli_connect_errno());
}?>
<?php
function find_all_pages(){
global $connection;
$query = "select * from pages ";
$query .= "order by position asc";
$page_set = mysqli_query($connection, $query);
confirm_query($page_set);
return $page_set;
}?>
<h2>Create Page</h2>
<form action="create_page.php" method="post">
<p>Subject Id:
<input type="number" name="subject_id" value="" />
</p>
<p>Book name:
<input type="text" name="book_name" value="" />
<br/><br/>
</p>
<p>Position:
<select name="position">
<?php
$page_set = find_all_pages();
$page_count = mysqli_num_rows($page_set);
for ($count=1; $count <= $page_count; $count++){
echo "<option value=\"1\">{$count}</option>";}
?>
</select>
</p>
<p>visible
<input type="radio" name="visible" value="0" /> No
<input type="radio" name="visible" value="0" /> Yes
</p>
<input type="submit" name ="submit" value="Create Page" />
</form>
create_page.php
<?php
if (isset($_POST["submit"])){
//Process the form
$subject_id = $_POST["subject_id"];
$book_name = $_POST["book_name"];
$position = $_POST["position"];
$visible = $_POST["visible"];
$book_name = mysqli_real_escape_string($connection, $book_name);
$subject_id = mysqli_real_escape_string($connection, $subject_id);
//Perform database query
$query = "insert into pages (";
$query .= " subject_id, 'book_name', position, visible";
$query .= " ) values ( ";
$query .= "$subject_id, '$book_name', $position, $visible ";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result){
//Success will redirect to manage content page
$_SESSION["message"] = "page was created. ";
redirect("manage_content.php");
} else {
//Failure will redirect to new subject page
//$_SESSION["message"] = "subject was not created. Please check following possible errors: <br/> "
//. " menu name is not blank <br/> visible is not blank";
//redirect("new_page.php");
echo "fail " . mysqli_error($connection) ;
}
}
?>
When i submitted the create page button, error appears:
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 ''book_name', position, visible ) values ( 121, 'how to win influence 1234', 1, 0'

You shouldn't have a ' character in the list of column_names .... column names are not string literals, they're column names. If they absolutely have to be quoted (e.g. if you have a column name that is a MySQL reserved word, then you use backticks(`) not quotes (')
$query = "insert into pages (";
$query .= " subject_id, book_name, position, visible";
$query .= " ) values ( ";
$query .= "$subject_id, '$book_name', $position, $visible ";
$query .= ")";
Now please learn about prepared statements and bind variables

There are security vulnerabilities in the way you are creating that query. But to specifically respond to your issue, get rid of the ' around 'book_name'.

Related

Function get_post and return mysqli_real_escape_string - PHP

I'm a beginner at coding (I just have a small experience with Visual Basic and Pascal) and now I'm trying to learn some Web Development using O'Reilly's book "Learning PHP, MySQL, JavaScript, CSS & HTML 5".
The problem is that he is using MySQL instead of MySQLi, so I need to do small changes when I'm following thought the exercises.
In a chapter called "Accessing MySQL databases using PHP" he built a form where the user can add a new book (with title name, author, year, category and ISBN) to the database. My problem is that I have some error than doesn't allow to see in the web page the new book submitted.
I'm not sure, but I think it has to be something with the get_post and mysqli_real escape_string part.
This is the code I've written:
<?php //sqltest.php
require_once 'login.php';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysqli_error($db_server));
mysqli_select_db($db_server, $db_database)
or die ("Unable to select database: " . mysqli_error($db_server));
//Deleting a record.
if (isset($_POST['delete']) && isset($_POST['isbn']))
{
$isbn = get_post('isbn');
$query = "DELETE FROM classics WHERE isbn = '$isbn'";
if (!mysqli_query($db_server,$query))
echo "DELETE failed: $query<br>" .
mysqli_error($query) . "<br><br>";
}
//Add new elements to the database.
if (isset($_POST['author']) && //Isset -> Determine if a variable is set and is not NULL.
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post($db_server, 'author');
$title = get_post($db_server, 'title');
$category = get_post($db_server, 'category');
$year = get_post($db_server, 'year');
$isbn = get_post($db_server, 'isbn');
}
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$category', '$year', '$isbn')";
//Displaying the form.
echo <<<_END
<form action = "sqltest.php" method="post"> <pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Category <input type="text" name="category" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysqli_query($db_server, $query);
if (!$result) die ("Database acess failed: " . mysqli_query_error($result));
$rows = mysqli_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysqli_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="isbn" value="$row[4]">
<input type="submit" value="DELETE RECORD"></form>
_END;
}
function get_post($db_server, $var)
{
return mysqli_real_escape_string($db_server, $_POST[$var]);
}
mysqli_close($db_server);
?>
Just to explain my problem better: I fill the form with the details from the new book and then I submitted it but the new book doesn't appear on the web page (like the ones added before using MySQL command line).
Thanks for your time,
David
There is an error in your code, specific the name of database columns.
$query = "INSERT INTO classics (author, title, category, year, isbn) VALUES ('$author', '$title', '$category', '$year', '$isbn');";

PHP checklist get ID and value and store it

So I have a form to add a new item to database with a checkbox as follows
So my difficulty is the checkbox. I can easily enough create the array for all items checked but I need an ID for them along with it. I've tried to think of many ways and searched a lot but I just can't think of a way to get the ID in a way that is then useable to me along with the name of the feature (checklist). Since I have to get each feature item and add it to the table houses_has_features.
<?php
$title = 'Add a new house';
require_once 'header.php';
require_once 'nav.php';
require_once 'mysqli-con.php';
$conn = new MYSQLI($hn, $un, $pw, $db);
// If house name and type is set then add them into the database
if( !empty($_POST['h_name']) && !empty($_POST['h_type']) ) {
$house_name = $conn->real_escape_string($_POST['h_name']);
$house_type = $conn->real_escape_string($_POST['h_type']);
//show names added
echo '<b>House name: </b>'.$house_name . '<br><b> House type:</b> ' . $house_type;
$query = "INSERT INTO `house_names` (`id`, `name`) VALUES (NULL, '$house_name')";
$result = $conn->query($query);
if (!$result) die ("<b class='text-danger'><p>Insert failed ERRROR: " . $conn->error. "</p>");
global $house_name_id;
$house_name_id = $conn->insert_id;
$query = "INSERT INTO `house_types` VALUES ('$house_name_id', '$house_type')";
$result = $conn->query($query);
if (!$result) die ("<b class='text-danger'><p>Insert failed ERRROR: " . $conn->error. "</p>");
} else {
global $house_name_id;
$house_name_id= NULL;
}
//Start container for page content
echo '<div class="container">';
//Display an error message if house name is filled in but not house type
if ( !empty($_POST['h_name']) && empty($_POST['h_type']) || empty($_POST['h_name']) && !empty($_POST['h_type']) ) {
echo "<p class='error-text'>* Please fill in both the house name and house type *</p>";
}
$query_feat = $conn->query('SELECT * FROM features');
$rows = $query_feat->num_rows;
$features_list = $_POST['check_list'];
$feature_id = $_POST['feature_id'];
//display checked boxes.
if(isset($_POST['check_list'])) {
for ($i=0; $i<sizeof($features_list); $i++){
//echo '<br>House name id:' . $house_name_id . '<br> $_POST[] = ' . "$features_list[]";
print_r($features_list); echo '<br>';
print_r($feature_id);
}
}
// Add house form
echo <<<_END
<h1>Add a house</h1>
</div>
<div class="container">
<form action="add.php" method="post">
<p>House Name: <input type="text" name="h_name"></p>
<p>House type: <input type="text" name="h_type"></p>
<b>features:</b>
<ul class="list-group">
_END;
for ($c = 0 ; $c < $rows ; ++$c){
$query_feat->data_seek($c);
$feat = $query_feat->fetch_array(MYSQLI_NUM);
echo '<li><input type="checkbox" name="check_list[]" value="' .$feat[1]. '">'.$feat[1].'</li>';
}
echo <<<_END
<ul>
<input class="btn-primary" type="submit" value="Submit">
</form>
</div>
_END;
require_once 'footer.php';
I'm really lost on this one any help would be greatly appreciated :)
change your value of checkbox to id or anything you want.
<li><input type="checkbox" name="check_list[]" value="' .$feat[0]. '">'.$feat[1].'</li>
$feat[1] => $feat[0] or else

Solving the return value of an SQL Query in an Associative Array

Once again I am at the mercy of your knowledge and hope you can help.
Actual question is the bold italics, however you won't be able to help without reading the information that I've given.
Background to Question - I'm creating a photography website (for my mum) using HTML, CSS, MySQL and PHP. I'm in the process of working on the database, specifically on allowing my mum to insert images into the database using this form (http://i.imgur.com/h4nXFFA.png). She has no idea how to code, therefore I need to make it easy for her.
Database Background (what you need to know) - I've got an image_tbl and album_tbl. The album_tbl is shown here - http://i.imgur.com/4GXh9MP.png - with each album having an ID and Name (forget the 'hidden'). The image_tbl is shown here - http://i.imgur.com/RgC35Nd.png - with the important part (for this question) being the albumName.
Aim - I've managed to populate the 'Insert a New Image' form with the albums from album_tbl (picture shows 'Exploration'). I want her to be able to click the AlbumName (so she knows what album to add to), yet I want the image she inserts to receive the albumID in the database. Here's a Pastebin of my code thus far.
http://pastebin.com/6v8kvbGH = The HTML Form, for helping me be aware of the 1st Form in the code...
http://pastebin.com/4X6abTey = PHP/MySQL Code. Here we have me calling the inputs in the form and using them in 2 SQL Queries. The first Query is aiming to get the albumID of the albumName that was entered, and this is where it goes wrong. The commented out statements (using //) are me error-checking, and albumName is passed on from the form. However, the number of rows returned from the 1st SQL Statement is 0, when it should be 1. This is where I need help as clearly something's wrong with my assoc array ...
2nd Aim - Once the 1st SQL Query is working, the 2nd SQL Query is hopefully going to input the required variables into image_tbl including the albumID I hopefully just got from the 1st SQL Query.
I hope this is all that's required, as far as I'm aware the people who understand this should be able to help with what I've given. Thanks very much in advance!
Jake
Someone asked me to paste the code - HTML Form:
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['albumName'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
Inserting the image using PHP/MySQL:
<?php
$username="root";
$password="";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumName = $_POST['albumName'];
// echo "album name is" . $albumName;
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
$albumID = $conn->query($sql);
// echo "Number of rows is " . $albumID->num_rows;
if ($albumID->num_rows > 0) {
// output data of each row
while($row = $albumID->fetch_assoc()) {
echo "Album ID: " . $row["albumID"]. "<br>";
}
} else {
echo "0 results";
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
This line:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
should be:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = '$albumName'";
since the album name is a string.
You should check for errors when you perform a query:
$albumID = $conn->query($sql) or die($conn->error);
You can't use $albumID in the INSERT query. Despite the name of the variable, it doesn't contain an album ID, it contains a mysqli_result object that represents the entire resultset of the query -- you can only use it with methods like num_rows and fetch_assoc() to extract information from the resultset.
What you can do is use a SELECT statement as the source of data in an UPDATE:
$stmt = $conn->prepare("INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT ?, ?, ?, ?, ?, ?, albumID
FROM album_tbl
WHERE albumName = ?";
$stmt->bind_param("sssssss", $name, $dateTime, $caption, $comment, $slideshow, $hidden, $albumName);
$stmt->execute();
Note that when you use a prepared query, you don't need to fix the quotes in $comment (which you should have done using $conn->real_escape_string($comment), not str_replace()).
Just to help you understand, this can also be done without a prepared query.
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT '$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', albumID
FROM album_tbl
WHERE albumName = '$albumName'";
First of all create a single database connection let say
db_connection.php
<?php
$username="root";
$password="1k9i2n8gjd";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
Then in your form or any php file that needs database connection you can just include the db_connection.php so that you have one database connection.
Note: I have change the value of option to albumId so that you dont need to query or select based on albumName because you already have the albumID passed in imagesInsert.php via $_POST
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
?>
<html>
<head>
<title>Admin Page | Alison Ryde's Photography</title>
<link rel="stylesheet" type="text/css" href="../../css/style.css">
</head>
<body>
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = $conn->query($sql);// mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['albumID'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
</html>
Then in your php code that inserts the data should be like this.
imagesInsert.php
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
Another piece of advice is to use prepared statementif your query is build by users input to avoid sql injection
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssss", $name, $dateTime, $caption,$new_comment,$slideshow,$hidden,$albumID);
$stmt->execute();
hope that helps :) good luck

Mupdate sql query return an error: limit 1

<?php
// find current order
$current_order_id = find_order_by_id($_GET['order']);
if(!$current_order_id){
redirect_to("orders.php");
}
?>
<?php
$id = $current_order_id["id"];
$menu_name = $_POST["menu_name"];
$address = $_POST["address"];
$contact = $_POST["contact"];
$transaction = $_POST["transaction"];
$flemingia = $_POST["flemingia"];
$goat_manual = $_POST["goat_manual"];
$lbc_tracking_no = $_POST["lbc_tracking_no"];
$visible = $_POST["visible"];
$query = "UPDATE orders SET ";
$query .= "menu_name = '{$menu_name}', ";
$query .= "address = '{$address}', ";
$query .= "contact = {$contact}, ";
$query .= "transaction = '{$transaction}', ";
$query .= "flemingia = {$flemingia}, ";
$query .= "goat_manual = {$goat_manual}, ";
$query .= "lbc_tracking_no = {$lbc_tracking_no}, ";
$query .= "visible = {$visible} ";
$query .= "WHERE id = {$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if($result){
die("Database connection failed. " . mysqli_error($connection));
}
?>
and this is the error I got:
Database connection failed: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 'LIMIT 1' at line 1
can someone explain why this is happen
i suspect that i pickup wrong id so i echo my query and i got! a right id
output of my query:
UPDATE orders SET menu_name = '', address = '', contact = , transaction = '', flemingia = , goat_manual = , lbc_tracking_no = , visible = WHERE id = 20 LIMIT 1
note: contact, flemingia, goat_manual, lbc_tracking_no, visible are all INT
===============================Update===================================
My Form
<h1>Create Order : <?php echo $current_order_id["menu_name"]; ?></h1>
<p class="error"><?php echo $message; ?></p>
<form action="edit_order.php" method="post">
<p><span>Name</span>:
<input type="text" name="menu_name" value="<?php echo $current_order_id["menu_name"]; ?>" />
</p>
<p><span>Address</span>:
<input type="text" name="address" value="<?php echo $current_order_id["address"]; ?>" />
</p>
<p><span>Contact Number</span>:
<input type="text" name="contact" value="<?php echo $current_order_id["contact"]; ?>" />
</p>
<p><span>Transaction</span>:
<input type="text" name="transaction" value="<?php echo $current_order_id["transaction"]; ?>" />
</p>
<p><span>Flemingia</span>:
<input type="text" name="flemingia" value="<?php echo $current_order_id["flemingia"]; ?>" />
</p>
<p><span>Goat Manual</span>:
<input type="text" name="goat_manual" value="<?php echo $current_order_id["goat_manual"]; ?>" />
</p>
<p><span>LBC Tracking NO.</span>:
<input type="text" name="lbc_tracking_no" value="<?php echo $current_order_id["lbc_tracking_no"]; ?>" />
</p>
<p><span>visible</span>:
<input type="radio" name="visible" value="0" <?php if($current_order_id["visible"] == 0){echo "checked";} ?> />No
<input type="radio" name="visible" value="1" <?php if($current_order_id["visible"] == 1){echo "checked";}?> />Yes
</p>
<input class="submit_btn" type="submit" name="submit" value="Edit Order" />
</form>
this is all my function
<?php
function redirect_to($new_location){
header("Location:" . $new_location);
exit;
}
function confirm_query($result_set){
if(!$result_set){
die("Database connection failed. ");
}
}
function find_all_order(){
global $connection;
$query = "SELECT * ";
$query .= "FROM orders";
$order_set = mysqli_query($connection, $query);
confirm_query($order_set);
return $order_set;
}
function find_order_by_id($order_id){
global $connection;
$query = "SELECT * ";
$query .= "FROM orders ";
$query .= "WHERE id = {$order_id} ";
$query .= "LIMIT 1";
$orderset = mysqli_query($connection, $query);
if(!$orderset){
die("Database connection failed:" . mysqli_error($connection));
}
if($order = mysqli_fetch_assoc($orderset)){
return $order;
}else{
return null;
}
}
?>
I think I know where the problem is. You need to use the multi_query() function.
Try this:
if(!$connection->multi_query($query)){
echo "Multi query failed: (" . $connection->errno . ") " . $connection->error;
}
instead of $result = mysqli_query($connection, $query);
Edit
Try this method then:
$query = "UPDATE orders SET menu_name = '$menu_name', address = '$address',
contact = $contact, transaction = '$transaction', flemingia = $flemingia,
goat_manual = $goat_manual, lbc_tracking_no = $lbc_tracking_no, visible = $visible
WHERE id = $id LIMIT 1";
$result = mysqli_query($connection, $query);
if(!$result){
die("Database connection failed. " . mysqli_error($connection));
}
else{
echo "Success";
}
or:
$query = "UPDATE orders SET menu_name = '".$menu_name."', address = '".$address."',
contact = $contact, transaction = '".$transaction."', flemingia = $flemingia,
goat_manual = $goat_manual, lbc_tracking_no = $lbc_tracking_no, visible = $visible
WHERE id = $id LIMIT 1";
$result = mysqli_query($connection, $query);
if(!$result){
die("Database connection failed. " . mysqli_error($connection));
}
else{
echo "Success";
}
However, if some of your entries contain hyphens, that could be a factor.
Original answer
You have quotes missing for some of your variables:
{$flemingia} - {$goat_manual} - {$lbc_tracking_no} - {$visible}
$query = "UPDATE orders SET ";
$query .= "menu_name = '{$menu_name}', ";
$query .= "address = '{$address}', ";
$query .= "contact = {$contact}, ";
$query .= "transaction = '{$transaction}', ";
$query .= "flemingia = '{$flemingia}', ";
$query .= "goat_manual = '{$goat_manual}', ";
$query .= "lbc_tracking_no = '{$lbc_tracking_no}', ";
$query .= "visible = '{$visible}' ";
$query .= "WHERE id = {$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
Edit: deleted {$contact} from the list, since OP said it is an int
However, you may need to put them back in, since this contact = , is part of your error message, along with the others.
Your {$id} did not have any and it shows up correctly in your echo'ed query.

On PHP form POST submission, add a variable to the URL

I'm building a single page application for finding a film based on genre. At the moment it uses the POST method on both the main form and the comments form.
The commments form currently gets the film ID using a GET method (this was chosen to avoid refreshing the page which resets the film suggestion process).
At the moment if I hit submit on the main form, the url changes to index.php? and the film successfully loads based on the criteria.
My question is: Why isn't my filmID echoing out in the main form? How can I stick the film ID into the current URL without using the GET method? So for instance if I typed in index.php?filmID=6 it would load up info about "The Dark Knight".
index.php (Trimmed by request)
//If submit comment pressed, get data and input
if(trim($_POST['submit']) == "Submit comment"){
$userID = $_SESSION['userID'];
$likeit = $_POST['yesornoList'];
$filmID = $_GET['filmID'];
$comment = clean_string($db_server, $_POST['commentBox']);
if ($comment != '') {
$query = "INSERT INTO comments (userID, filmID, comment, likeit)
VALUES ('$userID', '$filmID', '$comment', '$likeit')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server)) . $query;
echo $commentMessage = "<section>Thanks for your comment!</section>";
}
}else{
if (isset($_POST['genreList']) && ($_POST['genreList'] != "")){
$genre = clean_string($db_server, $_POST['genreList']);
//create the SQL query
$query = "SELECT * FROM films WHERE genreID=$genre ";
//$endquery = " AND (";
$endquery = "";
$orFlag = false;
if (isset($_POST['streamingCheckbox1']) && ($_POST['streamingCheckbox1'] != '')){
$endquery .= " netflix IS NOT NULL";
$orFlag = true;
}
if (isset($_POST['streamingCheckbox2']) && ($_POST['streamingCheckbox2'] != '')){
if($orFlag){
$endquery .= " OR ";
}
$endquery .= " lovefilmInstant IS NOT NULL";
$orFlag = true;
}
if (isset($_POST['streamingCheckbox3']) && ($_POST['streamingCheckbox3'] != '')){
if($orFlag){
$endquery .= " OR ";
}
$endquery .= " blinkbox IS NOT NULL";
}
if($endquery != "") $query .= " AND (" . $endquery . ")";
$query .= " ORDER BY (SELECT FLOOR(MAX(filmID) * RAND()) FROM films) LIMIT 0,1;";
//query the database
mysqli_select_db($db_server, $db_database);
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) . $query);
//if there are any rows, print out the contents
if ($row = mysqli_fetch_array($result)) {
//Whether to display links or not for purchase and streaming
$filmID = $row['filmID'];
//Body content for film
$str_result =
"<section> This is where the film details are
</section>"
. $commentMessage . "
<section>
<form id='frmFilmComments' action='index.php?filmID=" . $filmID . "#comments' method='post'>
<a id='comments' class='anchor'></a>
<h3>Comments</h3>
<p><span class='bold'>Did you like " . $row['filmName'] ."?</span></p>
<select class='selectbox' name='yesornoList'>
<option value='Yes'>Yes</option>
<option value='No'>No</option>
</select>
<p><span class='bold'>Provide your feedback here:</span></p>
<textarea id='commentBox' class='insertComment' rows='2' cols='30' name='commentBox'></textarea><br>
<input class='formButton' type='submit' id='submit' name='submit' value='Submit comment'/>
</form>
";
mysqli_free_result($result);
//Code to print comments goes here
}else{
$str_result = "<section><h3>Sorry</h3><p>We couldn't find any films that match your terms. </br> <a href='#findafilm'>Please try again.</a></p></section>";
}
}else{
//$str_result = "<section><h3>Sorry</h3><p>No genre was chosen.</br><a href='home.php'>Please try again.</a></p></section>";
}
$message = $str_result . $likedcomments . $dislikedcomments . "<section/>";
}
}
//Exisiting code to handle options list
?>
<div id="top" class="content container headerMargin">
<div class="content wrapper">
<form id="frmFilmFinder" action="index.php?filmID=<?php echo $filmID; ?>" method="post">
<section>
<h2>Welcome <?php echo $_SESSION['username'] ?>!</h2>
<p class="underHeader">You are now logged in and ready to use the Film Finder.</p>
</section>
<section>
<a class="anchor" id="findafilm"></a>
<h3>Find a film</h3>
<h4>Choose a genre:</h4>
<select class="selectbox" name="genreList">
<?php echo $str_options; ?>
</select>
<h4>Choose a streaming service:</h3>
<input type="checkbox" class="checkbox" id="streamingCheckbox1" name="streamingCheckbox1" value="Netflix"><span class="checkboxText">Netflix</span><br>
<input type="checkbox" class="checkbox" id="streamingCheckbox2" name="streamingCheckbox2" value="LoveFilm"><span class="checkboxText">LoveFilm Instant</span><br>
<input type="checkbox" class="checkbox" id="streamingCheckbox3" name="streamingCheckbox3" value="blinkbox"><span class="checkboxText">blinkbox</span><br>
<input type="submit" class="formButton filmSearch" id="submit" name="submit" value="Submit"/>
<p><span class="italic">Leave all unticked if you wish to buy the film</span></p>
</section>
</form>
<?php echo $message; ?>
</div>
</div>
Principally, you need to be sure that $filmID is set when you write out your forms. It is valid to pass it in the query string (accessible via $_GET['filmID'] even though you are posting the form. It will work and serve its purpose, but be sure to comment what you're doing and why so you remember next time.
You populate it as $filmID = $_GET['filmID'] but only inside the form processing for your comments form. That means it won't be set unless you're receiving a comment. You ought to move that higher in the logic, checking always if it is set.
// near the top, outside if() conditions:
$filmID = isset($_GET['filmID']) ? $_GET['filmID'] : null;
Consider storing it into $_SESSION['filmID'] the first time you set it and any time it changes, so you have it on any script that needs it.
Finally, a side issue mentioned in the comments thread, working with MySQLi is a start, begin familiarizing yourself with how prepared statements work with bound parameters via mysqli::prepare(). All your query input variables should be handled via bound parameters, eliminating the need for escaping. This is a general best practice.

Categories