I'm currently self studying PHP and right now, I'm trying to create a simple library system. And now, I'm having some trouble with the search option. I believe that my query and conditional statement are correct but I still can't show the output.
This are the codes:
<html>
<link rel="stylesheet" type="text/css" href="style.css">
<head>Home Page!</head>
<h1>List of Books</h1>
<?php include 'show.php'; ?>
<?php
require 'dbcon.php';
$Terror = $Aerror = $Derror = $Cerror = $matches = "";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$T = $_POST['title'];
$A = $_POST['Author'];
$D = $_POST['Desc'];
$C = $_POST['Category'];
$X = $_POST['Opt'];
$del_sql = "delete from a where Title = '".$T."' AND Author = '".$A."' ";
"delete from b where Title = '".$T."' AND Description = '".$D."' AND Category = '".$C."' ";
if($X == 'Add'){
$in_sql = "insert a (Title, Author) values ('".$T."', '".$A."'); insert b (Title, Description, Category) values ('".$T."', '".$D."', '".$C."')";
if(empty($T) || empty($A) || empty($D) || empty($C)){
if(empty($A)) $Aerror = "Fill up Author";
if(empty($T)) $Terror = "Fill up Title";
if(empty($D)) $Derror = "Fill up Description";
if(empty($C)) $Cerror = "Fill up Category";
}
else if(mysqli_multi_query($dbcon, $in_sql)){
echo "New recored added";
}
}
else if ($X == 'Del'){
if (mysqli_multi_query($dbcon, $del_sql)){
echo "Record deleted";
}
}
else if ($X == 'Search'){
$sea1_sql = "select count(Title) from a where Title = '".$T."'";
$sea_sql = mysqli_multi_query($dbcon, "select * from a where Title = '".$T."' AND Author = '".$A."'");
"select Description, Category from b where Title = '".$T."' AND Description = '".$D."' AND Category = '".$C."'";
if (mysqli_query($dbcon, $sea1_sql) > 0){
while ($row = mysqli_fetch_array($sea_sql)){
echo "<table class = fix>";
echo "<tr><th>Title</th> <th> ". $row['Title'] . " </th></tr>";
echo "<tr><th>Author </th> <th> ". $row['Author'] . " </th></tr>";
echo "<tr><th>Description </th> <th> ". $row['Description'] . " </th></tr>";
echo "<tr><th>Category </th> <th> ". $row['Category'] . " </th></tr>";
echo "</table><br>";
}
}
else if (mysqli_query($dbcon, $sea1_sql) < 0){
echo "Can't find data!";
}
}
}
?>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br>Title: <input type="text" name="title"> <?php echo $Terror; ?><br>
Author: <input type="text" name="Author"><?php echo $Aerror; ?><br>
Description: <input type="text" name="Desc"><?php echo $Derror; ?><br>
Category: <input type="text" name="Category"><?php echo $Cerror; ?><br>
<select name="Opt">
<option disabled selected>N/A</option>
<option value='Add'>Add</option>
<option value='Edit'>Edit</option>
<option value='Del'>Del</option>
<option value='Search'>Search</option>
</select><br>
<input type="submit" name="submit">
</form>
</body>
</html>
This is wrong:
if (mysqli_query($dbcon, $sea1_sql) > 0){
myqli_query() doesn't return the value of count(Title). You need to fetch the row.
$sea1_result = mysqli_query($dbcon, $sea1_sql);
$row = mysqli_fetch_assoc($sea1_result);
if ($row['count(Title)'] > 0) {
You're also using mysqli_multi_query() incorrectly. It doesn't return a mysqli_result object that you can fetch results from, it returns a boolean that indicates whether the first query was successful or got an error. You need to call mysqli_use_result() to get the results of each query, and then call mysqli_fetch_array() on this.
But it looks like you shouldn't be using mysqli_multi_query() at all. You want to get the rows from a and b for the same title together, not all a rows before all b rows. You should join the two tables:
$sea_result = mysqli_query("SELECT a.*, b.Description, b.Category
FROM a JOIN b ON a.Title = b.Title
WHERE a.Title = '$T' AND a.Author = 'A'
AND b.Description = '$D' AND b.Category = '$C'");
Related
I'm not sure how to describe it, so here's a video where I explain my problem.
I tried rearranging some of the code, as I do believe nothing is faulty, attempting to make sure that the table refreshes with the new data inside it, however every time I tried to place my code in a different order (executing the queries in different orders), it either functions differently than how I want it to function or it doesn't function at all.
Both queries do function separately, I'm just unsure why they're not working together.
Searchbar has the value seen inputted in the homepage on both my Search page and this page in question. However it was left blank for this page, which gave me the result of having the full table display which is what I wanted to happen. I'm just not sure how I can edit my code so, when submitted, it will display the newly added data.
My PHP:
<?php
$find = $_POST['searchbar'];
$host = "localhost";
$username = "FFF";
$pword = "L3FhqJNey8Op2qJY";
$database = "Project";
include 'includes/db.inc.php';
$Name2 = $_POST['Name'];
$YearOfRelease2 = $_POST['YearOfRelease'];
$Studio2 = $_POST['Studio'];
$Age2 = $_POST['Age'];
$Score2 = $_POST['Score'];
?>
My HTML:
<html>
<head>
<title>Add a Film - Films! Films! FILMS!</title>
</head>
<body>
<h1>Films! Films! FILMS!</h1>
<h2>Add a Film</h2>
<p>If you wish to add a film to our database, feel free to add data relating to the film in the respective boxes below. You should then refresh the page.</p>
<p>Add Film:</p>
<form method="POST" action="AddFilm.php">
<p>Name of Film: <input type="text" name="Name"></p>
<p>Year of Release: <input type="text" name="YearOfRelease"></p>
<p>Name of Studio: <input type="text" name="Studio"></p>
<p>Age Rating: <select name="Age" size="1">
<optgroup label="Select Age Rating">
<option value="U">U</option>
<option value="PG">PG</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="18">18</option>
</optgroup>
</select></p>
<p>Review Score: <input type="text" name="Score"></p>
<p><input type="submit" name="submit" value="Submit and Refresh"></p>
</form>
<?php
echo "<h2>$output</h2>";
$query_string = "SELECT * FROM movies WHERE Name LIKE '%$find%' OR YearOfRelease LIKE '%$find%' OR Studio LIKE '%$find%' OR Age LIKE '%$find%' OR Score LIKE '%$find%'";
$query_string2 = "INSERT INTO movies (Name, YearOfRelease, Studio, Age, Score) VALUES ('$Name2', '$YearOfRelease2', '$Studio2', '$Age2', '$Score2');";
if ($result = $mysqli->query($query_string2)) {
$output2 = $Name2 ." has been added to the database.";
echo "<p>$output2</p>";
} else {
echo ("Error performing query: " . $mysqli->error() );
}
$result->close();
if ($result = $mysqli->query($query_string)) {
echo "<table border='1'>";
echo "<tr><th>FilmID</th><th>Name</th><th>YearOfRelease</th><th>Studio</th><th>Age</th><th>Score</th></tr>";
while ($row = $result->fetch_object())
{
$FilmID = $row->FilmID;
$Name = $row->Name;
$YearOfRelease = $row->YearOfRelease;
$Studio = $row->Studio;
$Age = $row->Age;
$Score = $row->Score;
$output ="<tr><td> $FilmID";
$output = $output . "<td> $Name";
$output = $output . "<td> $YearOfRelease";
$output = $output . "<td> $Studio";
$output = $output . "<td> $Age";
$output = $output . "<td> $Score </tr>";
echo "<p>$output</p>";
}
echo "</table>";
echo "<hr>";
echo '<p>Back to Home Page</p>';
$result->close();
} else {
echo ("Error performing query: " . $mysqli->error() );
}
$mysqli->close();
?>
</body>
</html>
first of all, there are 3 table in my database which is:-
te_event, te_venue, te_category.
the te_event table display the categoryID, venueID, event description, title, date and price.
the te_venue table having venueID, venueName and location
the te_category having catID and catDesc.
here is the first page that admin need to select an event in order to update.
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link rel="stylesheet" type="text/css" href="test1.css">
<meta charset = "utf-8">
<title>
</title>
</head>
<body>
<div id="title">
<p><h1>Tyne Events</h1></p>
</div>
<div id="wrapper">
<div id="navbar" >
<ul class="nav">
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>
<form class="formright">
<input type="text" placeholder="Search">
<button type="submit">Search</button>
</form>
</li>
</ul>
</div>
<div id= "detailCenter">
<?php
include "database_conn.php";
$sqlEvent = "SELECT * FROM te_events
INNER JOIN te_venue ON te_events.venueID = te_venue.venueID
INNER JOIN te_category ON te_events.catID = te_category.catID
ORDER by eventTitle ";//select all event record
//query the statement
$event= mysqli_query ($conn , $sqlEvent)
or die (mysqli_error($conn));
?>
<h1>Select Event To Modify</h1>
<table border = "1" cellpadding="10" width=100% >
<thead>
<th>Title</th>
<th>Category</th>
<th>Venue Name</th>
<th>Location</th>
<th>Start Date</th>
<th>End Date</th>
<th>Price</th>
</thead>
<?php
//display all the event record
while ($row = mysqli_fetch_assoc ($event)){
//extract the field
$id = $row ["eventID"];
$title = $row ["eventTitle"];
$desc = $row ["eventDescription"];
$venue = $row ["venueName"];
$location = $row ["location"];
$category = $row ["catDesc"];
$eStart = $row ["eventStartDate"];
$eEnd = $row ["eventEndDate"];
$ePrice = $row ["eventPrice"];
//start a row
echo"<tr>\n";
//output the URL
echo "<td>\n";
echo "<div> <a href = \"allDetails.php?eventID=$id\">
$title</a></div>\n";
echo "</td>\n";
echo "<td>\n";
echo "<div> $category</div>\n";
echo "</td>\n";
echo "<td>\n";
echo "<div> $venue</div>\n";
echo "</td>\n";
echo "<td>\n";
echo "<div> $location</div>\n";
echo "</td>\n";
echo "<td>\n";
echo "<div>$eStart</div> \n";
echo "</td>\n";
echo "<td>\n";
echo "<div>$eEnd</div>\n";
echo "</td>\n";
echo "<td> \n";
echo "<div>$ePrice</div>\n";
echo "</td>\n";
}
?>
</table>
</div>
</body>
</html>
<?php
mysqli_close($conn);
?>
here is the page that admin can edit the event details
<?php
include "database_conn.php";
if(isset($_GET['eventID'])){
$id = $_GET["eventID"]; //get event id
}
else {
header ("Refresh : 3; url=admin.php");//redirect to choose title
die ("Please use the Choose Event Title List");
}
//get event id
$id = $_GET["eventID"];//get event id
//select event
$sqlEvent =" SELECT * FROM te_events
INNER JOIN te_venue ON te_events.venueID = te_venue.venueID
INNER JOIN te_category ON te_events.catID = te_category.catID
WHERE te_events.eventID =".$id;
//excute sql statemente
$event = mysqli_query($conn , $sqlEvent) or die (mysqli_error($conn));
$_GET = mysqli_fetch_assoc($event) or die (mysqli_error($conn));
//extract each field$
$title = $_GET ["eventTitle"];
$desc = $_GET ["eventDescription"];
$venueId = $_GET ["venueID"];
$venue = $_GET ["venueName"];
$location = $_GET ["location"];
$categoryId = $_GET ["catID"];
$category = $_GET ["catDesc"];
$eStart = $_GET ["eventStartDate"];
$eEnd = $_GET ["eventEndDate"];
$ePrice = $_GET ["eventPrice"];
?>
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link rel="stylesheet" type="text/css" href="test1.css">
<meta charset = "utf-8">
<title>
</title>
</head>
<body>
<div id="title">
<p><h1>Tyne Events</h1></p>
</div>
<div id="wrapper">
<div id="navbar" >
<ul class="nav">
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>
<form class="formright">
<input type="text" placeholder="Search">
<button type="submit">Search</button>
</form>
</li>
</ul>
</div>
<div id= "detailCenter">
<form id="updateEventDetail" method ="get" action ="updateEventDetail.php">
<fieldset>
<legend>Event details</legend>
<div><p>
<input type ="hidden" name ="eventID" value="<?=$eventID?>"/>
</p></div>
<div><p>
<label class="field" for="eTitle">Event title</label>
<input type ="text" name ="eventTitle" value="<?=$title?>"/>
</p></div>
<div><p>
<label class="field" for="cat">Category</label>
<?php
$sqlCategory ="SELECT DISTINCT catDesc FROM te_category ORDER BY 1";
//query sqlVenue
$rsCategory = mysqli_query ($conn ,$sqlCategory)
or die ("SQL ERROR :".mysqli_error($conn));
//create select item
echo"<select name=\"catDesc\">\n";
//iterate venue record
while ($_GET = mysqli_fetch_assoc($rsCategory)){
//populate select item
$category = $_GET[catDesc]; //get each venueName record
if($category==$category)
echo "<option value =\"$category\" selected>
$category</option>\n";
else{
echo "<option value =\"$venue\">
$category</option>\n";
}
}
echo"</select>\n";
?>
</p></div>
<div><p>
<label class="field" for="desc">Description</label>
<textarea style="resize:none" name="eventDescription" rows="10" cols="40" value="<?=$desc?>"><?=$desc?> </textarea>
</p></div>
<div>
<p>
<label class ="field" for="venue">Venue</label>
<?php
$sqlVenue ="SELECT DISTINCT venueName FROM te_venue ORDER BY 1";
//query sqlVenue
$rsVenue = mysqli_query ($conn ,$sqlVenue)
or die ("SQL ERROR :".mysqli_error($conn));
//create select item
echo"<select name=\"venueName\">\n";
//iterate venue record
while ($_GET = mysqli_fetch_assoc($rsVenue)){
//populate select item
$eVenue = $_GET[venueName]; //get each venueName record
if($eVenue==$venueName)
echo "<option value =\"$eVenue\" selected>
$eVenue</option>\n";
else{
echo "<option value =\"$venue\">
$eVenue</option>\n";
}
}
echo"</select>\n";
?>
</p>
</div>
<div><p>
<label class="field" for="location">Location</label>
<?php
$sqlLocation ="SELECT DISTINCT location FROM te_venue ORDER BY 1";
//query sqlLocation
$rsLocation = mysqli_query ($conn ,$sqlLocation)
or die ("SQL ERROR :".mysqli_error($conn));
//create select item
echo"<select name=\"location\">\n";
//iterate venue record
while ($_GET = mysqli_fetch_assoc($rsLocation)){
//populate select item
$eLocation = $_GET[location]; //get each location record
if($eLocation==$location)
echo "<option value =\"$eLocation\" selected>
$eLocation</option>\n";
else{
echo "<option value =\"$location\">
$eLocation</option>\n";
}
}
echo"</select>\n";
?>
</p></div>
<div><p>
<label class="field" for="sDate">Event Start Date</label>
<input name="eventStartDate" type="date" value="<?=$eStart?>"/>
</p></div>
<div><p>
<label class="field" for="eDate">Event End Date</label>
<input name="eventEndDate" type="date" value="<?=$eEnd?>"/>
</p></div>
<div><p>
<label class="field" for="ePrice">Event Price</label>
<input type="text" name="eventPrice" value="<?=$ePrice?>"readonly/>
</p></div>
<div><p>
<input type="submit" id="floatright" value="Update Event"/>
</p></div>
</fieldset>
</form>
</div>
</body>
</html>
<?php
mysqli_close($conn);
?>
the following code shows updatedetail.php
<?php
include "database_conn.php";
if(isset($_GET['eventID'])){
$id = $_GET["eventID"]; //get event id
}
//get all data submited
$id = $_GET ["eventID"];
$title = $_GET ["eventTitle"];
$desc = $_GET ["eventDescription"];
$venue = $_GET ["venueName"];
$location = $_GET ["location"];
$category = $_GET ["catDesc"];
$eStart = $_GET ["eventStartDate"];
$eEnd = $_GET ["eventEndDate"];
$ePrice = $_GET["eventPrice"];
$sqlUpdateEvent = " UPDATE te_event SET
eventTitle = '$title'
eventDescription = '$desc'
catDesc = '$category'
venueName = '$venue'
location = '$location'
eventStartDate = '$eStart'
eventEndDate = '$eEnd'
eventPrice = '$ePrice'
WHERE eventID = $id";
mysqli_query ($conn , $sqlUpdateEvent)
or die ("SQL ERROR :".mysqli_error($conn));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>update mvie comfirmmation</title>
<meta charset="utf-8">
</head>
<body>
<h1>update mvoie detials</h1>
<?php
echo "Title : $eventTitle \n";
echo "Category : $catDesc \n";
echo "Description : $eventDescription \n";
echo "Venue : $venueName \n";
echo "Location : $location \n";
echo "Start Date : $eventStartDate \n";
echo "End Date : $eventEndDate \n";
echo "Price : $eventPrice \n";
if(mysqli_affected_rows($conn)>0)
echo "<p> Event update successfully </p>\n";
else
echo "<p> Update Fail</p>\n";
?>
Choose Event
</body>
</html>
<?php
mysqli_close($conn);
?>
the error i get is
SQL ERROR :You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'eventDescription = 'The PLAYHOUSE Whitley Bay is delighted to
announce that Litt' at line 3
i edited my question by adding some code
i hopes it helps
thank you for helping.
Your each columns are missing comma separators(,) in your query, so add them like below:-
$sqlUpdateEvent = "UPDATE te_event SET eventTitle = '$title', eventDescription = '$desc',catDesc = '$category',venueName = '$venue',location = '$location',eventStartDate = '$eStart',eventEndDate = '$eEnd',eventPrice = '$ePrice' WHERE eventID = $id";
Suggestion:- Your query is open to SQL Injection, so try to read about prepared statements and use them.
Code enhancement:-
<?php
include "database_conn.php";
if(isset($_GET['eventID']) && isset($_GET["eventTitle"]) && isset($_GET["eventDescription"]) && isset($_GET["venueName"]) && isset($_GET["location"]) && isset($_GET["catDesc"]) && isset($_GET["eventStartDate"]) && isset($_GET["eventEndDate"]) && isset($_GET["eventPrice"]) ){
$id = $_GET["eventID"];
$title = $_GET["eventTitle"];
$desc = $_GET["eventDescription"];
$venue = $_GET["venueName"];
$location = $_GET["location"];
$category = $_GET["catDesc"];
$eStart = $_GET["eventStartDate"];
$eEnd = $_GET["eventEndDate"];
$ePrice = $_GET["eventPrice"];
$sqlUpdateEvent = " UPDATE te_event SET eventTitle = '$title',eventDescription = '$desc',catDesc = '$category',venueName = '$venue',location = '$location',eventStartDate = '$eStart',eventEndDate = '$eEnd',eventPrice = '$ePrice' WHERE eventID = $id";
mysqli_query ($conn , $sqlUpdateEvent) or die ("SQL ERROR :".mysqli_error($conn));
}else{
echo "all data is required";
}
?>
You are not using comma here is the query
$sqlUpdateEvent = " UPDATE te_event SET
eventTitle = '$title',
eventDescription = '$desc',
catDesc = '$category',
venueName = '$venue',
location = '$location',
eventStartDate = '$eStart',
eventEndDate = '$eEnd',
eventPrice = '$ePrice'
WHERE eventID = $id";
I am new to php still learning i have made a navigation with the drop down submenus its working when im inserting new item in navigation but the problem exist when i try to edit the same navigation i get the error in function everything seems fine need help.
![Edit Form][1]
Error:
<code>
Database Query Failed in get subject by idYou 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
</code>
functions.php
<code>
// Get Subject By ID
function get_subject_by_id($subject_id){
global $connection;
$query = "SELECT * FROM subjects WHERE id = {$subject_id} LIMIT 1";
$result_set = mysqli_query($connection, $query);
if(!$result_set){
die("Database Query Failed in get subject by id" . mysqli_error($connection));
}
if($subject_data = mysqli_fetch_array($result_set)) {
return $subject_data;
} else {
return null;
}
}
</code>
edit_subject.php
<code>
<?php include('includes/connection.php'); ?>
<?php require_once('includes/functions.php'); ?>
<?php
if(isset($_POST['submit'])) {
$id = $_GET['subj'];
$menu_name = $_POST['menu_name'];
$position = $_POST['position'];
$visible = $_POST['visible'];
$content = $_POST['content'];
$query = "UPDATE subjects SET menu_name = '{$menu_name}', position = {$position}, visible = {$visible}, content = '{$content}' WHERE id = {$id}";
$result_update = mysqli_query($connection, $query);
if(mysqli_affected_rows($connection) == 1){
$message = "The Subject was successfully created.";
} else {
}
}
?>
<?php
if(isset($_GET['subj'])){
$sel_subject = get_subject_by_id($_GET['subj']);
$sel_page = NULL;
} elseif (isset($_GET['page'])) {
$sel_subject = NULL;
$sel_page = get_page_by_id($_GET['page']);
} else {
$sel_subject = NULL;
$sel_page = NULL;
}
?>
<?php include('includes/header.php'); ?>
<div class="sidebar">
<ul class="sideNav">
<?php
$query_sub = "SELECT * FROM subjects";
$subject_set = mysqli_query($connection, $query_sub);
if(!$subject_set){
die("Database Query Failed1");
}
while($subject = mysqli_fetch_array($subject_set)){
?>
<li><?php echo $subject["menu_name"]; ?>
<?php
$query_page = "SELECT * FROM pages WHERE subject_id = {$subject["id"]}";
$page_set = mysqli_query($connection, $query_page);
if(!$page_set){
die("Database Query Failed2");
} ?>
<ul>
<?php
while($page = mysqli_fetch_array($page_set))
{
?><li><?php echo $page["menu_name"]; ?></li><?php
} ?>
</ul>
</li>
<?php } ?>
</ul>
<br>
+ Add a new Subject
</div><!-- end of sidebar -->
<h2>Edit Subject: <?php echo $sel_subject['menu_name']; ?></h2>
<div class="main">
<br/> <br/>
<?php if(!empty($message)) { ?> <p><?php echo $message; ?></p> <?php } ?>
<form action="edit_subject.php?subj=<?php $sel_subject['id']; ?>" method="post">
<fieldset>
<legend>Edit Subject:</legend>
<p>Subject Name:
<input type="text" name="menu_name" value="<?php echo $sel_subject['menu_name']; ?>">
</p>
<p>Position:
<select name="position">
<?php
$query_opt = "SELECT * FROM subjects ORDER BY position ASC";
$subject_opt = mysqli_query($connection, $query_opt);
if(!$subject_opt){
die("Database Query Failed3");
}
$subject_count = mysqli_num_rows($subject_opt);
for($count=1; $count <= $subject_count+1; $count++){
echo "<option value=\"{$count}\"";
if($sel_subject['position'] == $count){
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0"<?php if($sel_subject['visible'] == 0){ echo " checked"; } ?>> No
<input type="radio" name="visible" value="1"<?php if($sel_subject['visible'] == 1){ echo " checked"; } ?>> Yes
</p>
<p>Content:<br/>
<textarea name="content" rows="20" cols="150"><?php echo $sel_subject['content']; ?></textarea>
</p>
<p>
<input type="submit" name="submit" value="Add Subject" class="button-submit">
</p>
</fieldset>
</form>
<br /><br />
</div><!-- end of main -->
<?php include('includes/footer.php'); ?>
</code>
Are you sure that $subject_id in function get_subject_by_id() is not empty ? Try the below code after $query = "SELECT * FROM subjects WHERE id = {$subject_id} LIMIT 1"; in functions.php (only for testing) and make sure that your query is correct.
echo $query;
die();
you've missed the single quotes in the query string.
$query = "SELECT * FROM subjects WHERE id = {$subject_id} LIMIT 1";
should be
$query = "SELECT * FROM subjects WHERE id = '{$subject_id}' LIMIT 1";
youve also done it here.
$query = "UPDATE subjects SET menu_name = '{$menu_name}', position = {$position}, visible = {$visible}, content = '{$content}' WHERE id = {$id}";
should be
$query = "UPDATE subjects SET menu_name = '{$menu_name}', position = '{$position}', visible = '{$visible}', content = '{$content}' WHERE id = '{$id}'";
a note you dont need to wrap in {} for simple variables. You only need them if calling complex variables such as {$array['test']} as expained in this answer
Hello my name is Patrick and this is my first question, i'm sorry but i'm not very good in PHP. probably there are more improvements but this post is for the questions. (but improvements are also welcome)
Question:
You can choose a team of 2 monsters // The monster are selected form database
The question is: if you choose 1 monster how can i fix that you can't choose the same monster on option 2?
PHP CODE:
Action of the 2 sumbit buttons
<?php
session_start();
include("header.php");
if(!isset($_SESSION['uid'])){
echo "You must be logged in to view this page!";
}else{
if (isset($_POST['save'])) {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if($Result){
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5'){
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if($Result){
echo 'Team is aangepast!';
}
}
echo '';}
?>
Get the monsters form database and put it in a select list
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option4 = '';
while($row = mysql_fetch_assoc($get))
{
$option4 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
Show the selected item
<?php
$k4 = mysql_query("
SELECT user_team.m_keuze4, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze4=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row4 = mysql_fetch_assoc($k4))
{
$k4_1 = ''.$row4['m_keuze4'].' - '.$row4['monster'].' - '.$row4['type'].' - '.$row4['attack'].' - '.$row4['defense'].'';
}
?>
Option 5 is the same code as 4:
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option5 = '';
while($row = mysql_fetch_assoc($get))
{
$option5 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
<?php
$k5 = mysql_query("
SELECT user_team.m_keuze5, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze5=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row5 = mysql_fetch_assoc($k5))
{
$k5_1 = ''.$row5['m_keuze5'].' - '.$row5['monster'].' - '.$row5['type'].' - '.$row5['attack'].' - '.$row5['defense'].'';
}
?>
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form>
<form action="team.php" method="post">
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
In php the best you can do check the option once its posted:
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST,'option4') == filter_input(INPUT_POST,'option5')){
echo "Sorry. You can't select the same monster twice";
}else{
//your db insert logic goes here
}
}
It would be a good idea to also include some javascript to alert the user before they submit the form. This example uses jQuery
$('[name="option4"],[name="option5"]').change(function(){
if ($('[name="option4"]').val() == $('[name="option5"]').val()){
alert('you already chose that monster, please choose another');
}
});
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form> <!-- remove this line-->
<form action="team.php" method="post"> <!-- and this line-->
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
$('[name="option4"],[name="option5"]').change(function () {
if ($('[name="option4"]').val() == $('[name="option5"]').val()) {
alert('you already chose that monster, please choose another');
}
});
});
</script>
Action of the 2 sumbit buttons
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST, 'option4') == filter_input(INPUT_POST, 'option5')) {
echo "Sorry. You can't select the same monster twice";
} else {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if ($Result) {
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5') {
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if ($Result) {
echo 'Team is aangepast!';
}
}
}
}
Edit again,
Demo Fiddle of js
why when i try to search mysql database, it shows 0 result? i altered the table into FULLTEXT etc properly. What am I missing? I have put the very basic search exercise code down here. I want to search into my table 'products' and extract the details from there. but no luck
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$search_output = "";
if(isset($_POST['searchquery']) && $_POST['searchquery'] != ""){
$searchquery = preg_replace('#[^a-z 0-9?!]#i', '', $_POST['searchquery']);
if($_POST['filter1'] == "Whole Site"){
$sqlCommand = "SELECT product_name AS name, details AS details FROM products WHERE MATCH (product_name ,details) AGAINST ('$searchquery' IN BOOLEAN MODE)";
}
require_once("storescripts/connect_to_mysqli.php");
$query = mysqli_query($myConnection,$sqlCommand) or die(mysqli_error($myConnection));
$count = mysqli_num_rows($query);
if($count > 1){
$search_output .= "<hr />$count results for <strong>$searchquery</strong><hr />$sqlCommand<hr />";
while($row = mysqli_fetch_array($query)){
$name = $row["name"];
$details= $row["details"];
$search_output .= "Name: '.$name.' - '.$details.'<br />";
} // close while
} else {
$search_output = "<hr />0 results for <strong>$searchquery</strong><hr />$sqlCommand";
}
}
?>
<html>
<head>
</head>
<body>
<h2>Search the Exercise Tables</h2>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Search For:
<input name="searchquery" type="text" size="44" maxlength="88">
Within:
<select name="filter1">
<option value="Whole Site">Whole Site</option>
</select>
<input name="myBtn" type="submit">
<br />
</form>
<div>
<?php echo $search_output; ?>
</div>
</body>
</html>
Change this:
$sqlCommand = "SELECT product_name AS name, details AS details FROM products WHERE MATCH (product_name ,details) AGAINST ('".$searchquery."' IN BOOLEAN MODE)";
i have changed
AGAINST ('$searchquery' IN
to
AGAINST ('".$searchquery."' IN
Problem is there with your if part as:
replace your current :
if($_POST['filter1'] == "Whole Site")
{
$sqlCommand = "SELECT product_name AS name, details AS details FROM products WHERE MATCH (product_name ,details) AGAINST ({$searchquery} IN BOOLEAN MODE)";
}
In case it couldnt get to query due to if statement add:
else {
echo "No seqrch query found";
}
hope it works now