I'm getting the error message in the title for the following code, the page is for adding sub categories to my forum.
<?php
include '../includes/connect.php';
include '../header.php';
echo '<h2>Create a Sub category</h2>';
if($_SESSION['signed_in'] == false | $_SESSION['user_level'] != 1 )
{
//the user is not an admin
echo 'Sorry, you do not have sufficient rights to access this page.';
}
else
{
//the user has admin rights
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
//the form hasn't been posted yet, display it
echo '<form method="post" action="">
Category name: ';
$sql = "SELECT cat_id, cat_name, cat_description FROM categories";
$result = mysql_query($sql);
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select><br />';
echo 'Sub category name: <input type="text" name="sub_cat_name" /><br />
Sub category description:<br /> <textarea name="sub_desc" /></textarea><br /><br />
<input type="submit" value="Add Sub Category" />
</form>';
}
else
{
//the form has been posted, so save it
$sql = "INSERT INTO subcategories(c_id, sub_cat_name, sub_desc)
VALUES('" . $cat_id . ", " . $sub_cat_name . ", " . $sub_desc . "')";
$result = mysql_query($sql) or die (mysql_error());
echo 'The sub category <b>" . $sub_cat_name . "</b> has been added under the main category <b>" . $cat_name . "</b>';
if(!$result)
{
//something went wrong, display the error
echo 'Error' . mysql_error();
}
else
{
echo 'New Sub category succesfully added.';
}
}
}
; ?>
My categories table is structured like so..
cat_id
cat_desc
My subcategories table is structured like so..
id(AI)
c_id
sub_cat_name
sub_desc
If I haven't provided enough information please let me know.
You've not quoted things properly here:
VALUES('" . $cat_id . ", " . $sub_cat_name . ", " . $sub_desc . "')";
You need
VALUES('" . $cat_id . "', '" . $sub_cat_name . "', '" . $sub_desc . "')";
Note the extra single quotes.
You missed some quotes. Change
VALUES('" . $cat_id . ", " . $sub_cat_name . ", " . $sub_desc . "')";
to
VALUES('" . $cat_id . "', '" . $sub_cat_name . "', '" . $sub_desc . "')";
Related
i cant seem to make each movie appear under their respective date and have a correct time dropdown menu for the movie time selection
$sql_date = "SELECT DISTINCT sDate, sTitle FROM movieScreenings ";
$result_date = mysqli_query($db, $sql_date);
while($row = mysqli_fetch_array($result_date)) {
echo "<h2>" . $row['sDate'] . "</h2>";
$sql_movie = "SELECT * FROM movieList, movieScreenings WHERE title = '" . $row['sTitle'] . "'";
$result_movie = mysqli_query($db, $sql_movie);
while($row2 = mysqli_fetch_array($result_movie)) {
echo "<div class='box'>
<img class='poster' src='posters/" . $row2['poster'] . "'/>
<h2>" . $row2['title'] . "</h2>
<p>" . $row2['description'] . "</p>";
$sql_time = "SELECT DISTINCT sTime FROM movieScreenings WHERE sTitle = '" . $row2['title'] . "' AND sDate = '" . $row['sDate'] . "'";
$result_time = mysqli_query($db, $sql_time);
while($row3 = mysqli_fetch_array($result_time)) {
echo "<select name='sTime'>
<option value='" . $row3['sTime'] . "'>" . $row3['sTime'] . "</option>
</select>";
echo "</div>";
}
}
}
mysqli_free_result($result_date);
mysqli_free_result($result_movie);
mysqli_free_result($result_time);
// Close connection
mysqli_close($db);
You probably want to sort your first query by sDate with ORDER BY sDate.
In your second query you are again selecting from movieScreenings which is not necessary because I imagine all the data you are accessing (poster, title, description) is stored in movieList.
Thirdly, in your last while loop you are repeating the <select> tag for every screening time. This will result in multiple dropdown inputs. Also, you are including the closing </div> tag in this loop. So only loop the <option> tag.
With these changes your code would look like this:
$sql_date = "SELECT DISTINCT sDate, sTitle FROM movieScreenings ORDER BY sDate ASC";
$result_date = mysqli_query($db, $sql_date);
while($row = mysqli_fetch_array($result_date)) {
echo "<h2>" . $row['sDate'] . "</h2>";
$sql_movie = "SELECT * FROM movieList WHERE title = '" . $row['sTitle'] . "'";
$result_movie = mysqli_query($db, $sql_movie);
while($row2 = mysqli_fetch_array($result_movie)) {
echo "<div class='box'>
<img class='poster' src='posters/" . $row2['poster'] . "'/>
<h2>" . $row2['title'] . "</h2>
<p>" . $row2['description'] . "</p>";
$sql_time = "SELECT DISTINCT sTime FROM movieScreenings WHERE sTitle = '" . $row2['title'] . "' AND sDate = '" . $row['sDate'] . "'";
$result_time = mysqli_query($db, $sql_time);
echo "<select name='sTime'>";
while($row3 = mysqli_fetch_array($result_time)) {
echo "<option value='" . $row3['sTime'] . "'>" . $row3['sTime'] . "</option>";
}
echo "</select>";
echo "</div>";
}
}
...
And lastly, I would suggest using ID's as your foreign keys to prevent duplicates in the future. There might be multiple movies with the same title.
I am making e-commerce site and add to basket script not doing anything
I expect it to insert data into shopping basket from products page that is working perfectly fine. Please have a look and help me figure it out.. it is not giving any syntax error or parse error it just dont do anything and when I click buy it just redirect me to homepage
<?php
error_reporting(E_ALL);
session_start();
require("db.php");
require("functions.php");
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$prodres = mysqli_query($prodsql);
$numrows = mysqli_num_rows($prodres);
$prodrow = mysqli_fetch_assoc($prodres);
if($numrows == 0)
{
header("Location: " . $config_basedir);
} else {
if($_POST['submit'])
{
if($_SESSION['SESS_ORDERNUM'])
{
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM'] . ", "
. $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
} else {
if($_SESSION['SESS_LOGGEDIN'])
{
$sql = "INSERT INTO orders(customer_id, registered, date) VALUES("
. $_SESSION['SESS_USERID'] . ", 1, NOW())";
mysqli_query($sql);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM']
. ", " . $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
} else {
$sql = "INSERT INTO orders(registered, date, session) VALUES("
. "0, NOW(), '" . session_id() . "')";
mysqli_query($sql);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM'] . ", " . $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
}
}
$totalprice = $prodrow['price'] * $_POST['amountBox'] ;
$updsql = "UPDATE orders SET total = total + "
. $totalprice . " WHERE id = "
. $_SESSION['SESS_ORDERNUM'] . ";";
mysqli_query($updres);
header("Location: " . $config_basedir . "showcart.php");
} else {
require("header.php");
echo "<form action='addtobasket.php?id="
. $_GET['id'] . "' method='POST'>";
echo "<table cellpadding='10'>";
echo "<tr>";
if(empty($prodrow['image']))
{
echo "<td><img src='./productimages/dummy.jpg' width='50' alt='"
. $prodrow['name'] . "'></td>";
} else {
echo "<td><img src='./productimages/" . $prodrow['image']
. "' width='50' alt='" . $prodrow['name']
. "'></td>";
}
echo "<td>" . $prodrow['name'] . "</td>";
echo "<td>Select Quantity <select name='amountBox'>";
for($i=1;$i<=100;$i++)
{
echo "<option>" . $i . "</option>";
}
echo "</select></td>";
echo "<td><strong>£"
. sprintf('%.2f', $prodrow['price'])
. "</strong></td>";
echo "<td><input type='submit' name='submit' value='Add to basket'></td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
}
require("footer.php");
error_reporting(E_ALL);
?>
there are two redirects that makes your user return to your home page
first:
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
make sure $_GET['id] has valid value
second:
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$numrows = mysqli_num_rows($prodres);
// ...
if($numrows == 0)
{
header("Location: " . $config_basedir);
}
check your query in this line:
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
make sure it returns not an empty results ( $numrows == 0 )
Test it first on your DBMS front-end
I have created a foreach loop to add data to a MySQL database and I am receiving the error "mysqli::query(): Couldn't fetch mysqli" after the first line has been added to the database.
PHP DB CONNECTION
$db = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
I then have another chunk of script which collects the data I require. The data is then added to the foreach insert loop
PHP FOREACH
foreach($RSS_DOC->channel->item as $RSSitem)
{
$item_id = md5($RSSitem->title);
$fetch_date = date("Y-m-j G:i:s");
$item_title = $RSSitem->title;
$item_date = date("Y-m-j G:i:s", strtotime($RSSitem->pubDate));
$item_url = $RSSitem->link;
echo "Processing item '" , $item_id , "' on " , $fetch_date , "<br/>";
echo $item_title, " - ";
echo $item_date, "<br/>";
echo $item_url, "<br/>";
$sql = "INSERT INTO rssingest (item_id, feed_url, item_title, item_date, item_url, fetch_date)
VALUES ('" . $item_id . "', '" . $feed_url . "', '" . $item_title . "', '" . $item_date . "', '" . $item_url . "', '" . $fetch_date . "')";
if ($db->query($sql) === TRUE) { // <- THIS IS LINE 170
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
}
The first line is added to the database without a problem. The second line and every line after that one returns "mysqli::query(): Couldn't fetch mysqli on line 170".
Any ideas where I may be going wrong?
The problem may be the $db->close() inside the loop. Try closing the database after the loop.
foreach($RSS_DOC->channel->item as $RSSitem)
{
$item_id = md5($RSSitem->title);
$fetch_date = date("Y-m-j G:i:s");
$item_title = $RSSitem->title;
$item_date = date("Y-m-j G:i:s", strtotime($RSSitem->pubDate));
$item_url = $RSSitem->link;
echo "Processing item '" , $item_id , "' on " , $fetch_date , "<br/>";
echo $item_title, " - ";
echo $item_date, "<br/>";
echo $item_url, "<br/>";
$sql = "INSERT INTO rssingest (item_id, feed_url, item_title, item_date, item_url, fetch_date)
VALUES ('" . $item_id . "', '" . $feed_url . "', '" . $item_title . "', '" . $item_date . "', '" . $item_url . "', '" . $fetch_date . "')";
if ($db->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
}
$db->close();
I am able to get my script to parse the items and insert into mySQL OK when using the Channel->items. I now need to insert the url of the thumbnail which is located in items but in a sub-item "folder" for lack of knowing what to call it, but cannot get to it since its a in another level of the item "media:thumbnail" the rss feed is: http://feeds.bbci.co.uk/sport/0/audiovideo/rugby-league-av/rss.xml#
libxml_use_internal_errors(true);
$RSS_DOC = simpleXML_load_file($feed_url);
if (!$RSS_DOC) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
/* Get title, link, managing editor, and copyright from the document */
$rss_title = $RSS_DOC->channel->title;
$rss_link = $RSS_DOC->channel->link;
$rss_description = $RSS_DOC->channel->description;
$rss_copyright = $RSS_DOC->channel->guid;
$rss_date = $RSS_DOC->channel->pubDate;
//Loop through each item in the RSS document
foreach($RSS_DOC->channel->item as $RSSitem)
{
$item_id = md5($RSSitem->title);
$fetch_date = date("Y-m-j G:i:s"); //NOTE: we don't use a DB SQL function so its database independent
$item_title = $RSSitem->title;
$item_description = $RSSitem->description;
$item_date = date("Y-m-j G:i:s", strtotime($RSSitem->pubDate));
$item_url = $RSSitem->link;
$image_url =($RSSitem->media:thumbnails)->url;
echo "Processing item '" , $item_id , "' on " , $fetch_date , "<br/>";
echo $item_title, " - ";
echo $item_date, "<br/>";
echo $item_description, "<br/>";
echo $item_url, "<br/>";
echo $image_url, "<br/>";
// Does record already exist? Only insert if new item...
$item_exists_sql = "SELECT item_id FROM $db_database.`rssingest` where item_id = '" . $item_id . "'";
$item_exists = mysqli_query($db,$item_exists_sql);
if(mysqli_num_rows($item_exists)<1)
{
echo "<font color=green>Inserting new item..</font><br/>";
$item_insert_sql = "INSERT INTO $db_database.`rssingest`(item_id, feed_url, item_title, item_date, item_url, fetch_date,image_url) VALUES ('" . $item_id . "', '" . $feed_url . "', '" . $item_title . "', '" . $item_date . "', '" . $item_url . "', '" . $fetch_date . "', '" . $image_url . "')";
$insert_item = mysqli_query($db,$item_insert_sql);
}
else
{
echo "<font color=blue>Not inserting existing item..</font><br/>";
}
echo "<br/>";
}
I recently modified some code to allow for my quiz.php script to accommodate multiple quizzes as opposed to just one. To do this I sent along the quiz_id and quiz_title variables when the user clicks the link for the quiz and I receive them using $_GET. However, once the quiz form is submitted the quiz_id column no longer updates in the high_score table.
Here is the code for quiz.php
<?php
// Start the session
require_once('startsession.php');
// Insert the Page Header
$page_title = "Quiz Time!";
require_once('header.php');
require_once('connectvars.php');
// Make sure user is logged in
if (!isset($_SESSION['user_id'])) {
echo '<p>Please log in to access this page.</p>';
exit();
}
// Show navigation menu
require_once('navmenu.php');
// Connect to database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Declare $quiz_id
$quiz_title = $_GET['title'];
$quiz_id = $_GET['id'];
// print_r($quiz_title);
// print_r($quiz_id);
// Grab list of question_id's for this quiz
$query = "SELECT question_id FROM question WHERE quiz_id = '" . $quiz_id . "'";
$data = mysqli_query($dbc, $query);
$questionIDs = array();
while ($row = mysqli_fetch_array($data)) {
array_push($questionIDs, $row['question_id']);
}
// Create empty responses in 'quiz_response' table
foreach ($questionIDs as $questionID) {
$query = "INSERT INTO quiz_response (user_id, question_id) VALUES ('" . $_SESSION['user_id'] . "', '" . $questionID . "')";
mysqli_query($dbc, $query);
}
// If form is submitted, update choice_id column of quiz_response table
if (isset($_POST['submit'])) {
// Inserting choices into the response table
foreach ($_POST as $choice_id => $choice) {
$query = "UPDATE quiz_response SET choice_id = '$choice', answer_time=NOW() " .
"WHERE response_id = '$choice_id'";
mysqli_query($dbc, $query);
}
// Update the 'is_correct' column
// Pull all is_correct data from question_choice table relating to specific response_id
$total_Qs = 0;
$correct_As = 0;
foreach ($_POST as $choice_id => $choice) {
$query = "SELECT qr.response_id, qr.choice_id, qc.is_correct " .
"FROM quiz_response AS qr " .
"INNER JOIN question_choice AS qc USING (choice_id) " .
"WHERE response_id = '$choice_id'";
$data=mysqli_query($dbc, $query);
// Update is_correct column in quiz_response table
while ($row = mysqli_fetch_array($data, MYSQLI_ASSOC)) {
$total_Qs ++;
if ($row['is_correct'] == 1) {
$query2 = "UPDATE quiz_response SET is_correct = '1' " .
"WHERE response_id = '$row[response_id]'";
mysqli_query($dbc, $query2);
$correct_As ++;
}
}
}
// Update high_score table with $correct_As
$quiz_id = $_POST['quiz_id'];
$query = "INSERT INTO high_score " .
"VALUES ('0', '" . $_SESSION['user_id'] . "', '" . $quiz_id . "', '" . $correct_As . "', NOW())";
mysqli_query($dbc, $query);
// Display score after storing choices in database
echo 'You got ' . $correct_As . ' out of ' . $total_Qs . ' correct';
exit();
mysqli_close($dbc);
}
// Grab the question data from the database to generate the form
$Q_and_Cs = array();
foreach ($questionIDs as $questionID) {
$query = "SELECT qr.response_id AS r_id, qr.question_id, q.question " .
"FROM quiz_response AS qr " .
"INNER JOIN question AS q USING (question_id) " .
"WHERE qr.user_id = '" . $_SESSION['user_id'] . "' " .
"AND qr.question_id = '" . $questionID . "'";
$data = mysqli_query($dbc, $query)
or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $query");
// Store in $questions array, then push into $Q_and_Cs array
while ($row = mysqli_fetch_array($data, MYSQL_ASSOC)) {
print_r($row);
$questions = array();
$questions['r_id'] = $row['r_id'];
$questions['question_id'] = $row['question_id'];
$questions['question'] = $row['question'];
// Pull up the choices for each question
$query2 = "SELECT choice_id, choice FROM question_choice " .
"WHERE question_id = '" . $row['question_id'] . "'";
$data2 = mysqli_query($dbc, $query2);
while ($row2 = mysqli_fetch_array($data2, MYSQL_NUM)) {
$questions[] = $row2[0];
$questions[] = $row2[1];
}
array_push($Q_and_Cs, $questions);
}
}
mysqli_close($dbc);
// Generate the quiz form by looping through the questions array
echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
echo '<h2>' . $quiz_title . '</h2>';
$question_title = $Q_and_Cs[0]['question'];
echo '<label for="' . $Q_and_Cs[0]['r_id'] . '">' . $Q_and_Cs[0]['question'] . '</label><br />';
foreach ($Q_and_Cs as $Q_and_C) {
// Only start a new question if the question changes
if ($question_title != $Q_and_C['question']) {
$question_title = $Q_and_C['question'];
echo '<br /><label for="' . $Q_and_C['r_id'] . '">' . $Q_and_C['question'] . '</label><br />';
}
// Display the choices
// Choice #1
echo '<input type="radio" id="' . $Q_and_C['r_id'] . '" name="' . $Q_and_C['r_id'] . '" value="' . $Q_and_C[0] . '" />' . $Q_and_C[1] . '<br />';
// Choice#2
echo '<input type="radio" id="' . $Q_and_C['r_id'] . '" name="' . $Q_and_C['r_id'] . '" value="' . $Q_and_C[2] . '" />' . $Q_and_C[3] . '<br />';
// Choice #3
echo '<input type="radio" id="' . $Q_and_C['r_id'] . '" name="' . $Q_and_C['r_id'] . '" value="' . $Q_and_C[4] . '" />' . $Q_and_C[5] . '<br />';
// Choice #4
echo '<input type="radio" id="' . $Q_and_C['r_id'] . '" name="' . $Q_and_C['r_id'] . '" value="' . $Q_and_C[6] . '" />' . $Q_and_C[7] . '<br />';
}
echo '<br /><br />';
echo '<input type="hidden" name="quiz_id" value"'.$quiz_id.'" />';
echo '<input type="submit" value="Grade Me!" name="submit" />';
echo '</form>';
// echo 'Quiz_id: '.$quiz_id.'<br />';
// Insert the page footer
require_once('footer.php');
?>
Here is the code for quizlist.php
// Determine number of quizes based on title in quiz table
$query = "SELECT * FROM quiz";
$data = mysqli_query($dbc, $query);
// Loop through quiz titles and display links for each
while ($row = mysqli_fetch_array($data, MYSQL_ASSOC)) {
echo '' . $row['title'] . '<br />';
}
mysqli_close($dbc);
My problem has to do with the piece of code
$query = "INSERT INTO high_score " .
"VALUES ('0', '" . $_SESSION['user_id'] . "', '" . $quiz_id . "', '" . $correct_As . "', NOW())";
It works when I substitute a number (i.e. 2) in the place of $quiz_id, but in order for the script to work for different quizzes I need to be able to use a different quiz_id for different quizzes.
I'm having trouble taking the variable from quizlist.php using $_GET and then passing it along as a hidden value when the form is submitted. Am I doing something incorrect? Or am I missing something completely obvious? I'd appreciate any help! Thanks...
On the first clue, it seems to me that you're getting your $quiz_id form GET request (and that's correct), but you have a condition
if (isset($_POST['submit'])) {
which is fulfilled only when form is submitted (POST request), not link clicked. So all the code under this condition is not executed when you click the link