Can't display data from my DATABASE Server - php

<?php
//connection to the database
try {
$pdo = new PDO('mysql:host=localhost;dbname=frostedc_movies;charset=utf8',
frostedc_user, 'pass');
echo "connected";
}
catch(PDOException $e) {
echo $e; //2
}
// select everything from the news table
$query = "SELECT * FROM movie";// Table name NOT database name
foreach ($pdo->query($query) as $row) {
echo "<table border='1'>";
echo "<tr>";
echo "<td width='150'>".$row['movietitle']."</td>";
echo "<td width='150'>".$row['genre']."</td>";
echo "<td width='150'>".$row['LastViewed']."</td>";
echo "<td width='150'>".$row['Location']."</td>";
echo "</tr>";
}
echo "</tr>";
echo "</table>";
echo "<br>";
echo "
<form>
<p>Please Enter a Movie Title</p>
<input type='text' name='new_movie' />
<input type='submit' value='Submit' />
</form>";
echo "
<form>
<p>Please Enter the Genre</p>
<input type='text' name='movie_genre' />
<input type='submit' value='Submit' />
</form>";
echo "
<form>
<p>Please Enter the Last View Date</p>
<input type='text' name='last_view' />
<input type='submit' value='Submit' />
</form>";
echo "
<form>
<p>Please Enter the Location</p>
<input type='text' name='movie_loca' />
<input type='submit' value='Submit' />
</form>";
$pdo = null;
?>
this is the new updated code. I am trying to use the inputs to enter data into my database.
I have researched how to do this, but so far I haven't got anything to work. Any thoughts? Also would it be easier for me to use include and make the inputs in html? if so could i use them to enter the data into the db?

You are doing 2 wrong things here
First : Mixing PDO with MySQL
Second : $query = "SELECT * FROM myDB"; You cant select from a Database.. You need to do a SELECT from your TABLE ! (Are you sure myDB is your table ?)

As you have tagged your question PDO I have removed all unneeded code from your example.
<?php
//connection to the database
try {
$pdo = new PDO('mysql:host=localhost;dbname=frostedc_movies;charset=utf8',
user, 'password'); //1
echo "connected";
}
catch(PDOException $e) {
echo $e; //2
}
// select everything from the news table
$query = "SELECT * FROM myTable";// Table name NOT database name
echo "<table>";
echo "<tr>";
foreach ($pdo->query($query) as $row) {//3
echo "<td>".$row['movietitle']."</td>";
echo "<td>".$row['genre']."</td>";
echo "<td>".$row['LastViewed']."</td>";
echo "<td>".$row['Location']."</td>";
}
echo "</tr>";
echo "</table>";
// disconnect from the database
$pdo = null;//5
?>
The number comments
1 Setting character set Manual
2 Echoing error message only for development.In production you should either do something with it or remove try/catch.
3 As there are no parameters use query()
4 For utf8 Prior to PHP 5.3.6
5 Changed mysql_close();(mysql_) to $pdo = null; (PDO)

<?php // connect to the database
$host = 'localhost';
$username = 'user';
$pass = 'password';
$conn=mysql_connect($host,$username,$pass)or die(mysql_error());
mysql_select_db("myDB");
// select everything from the news table
$query = "SELECT * FROM news";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<table>
<tr>
<td>".$row['movietitle']."</td>
<td>".$row['genre']."</td>
<td>".$row['LastViewed']."</td>
<td>".$row['Location']."</td>
</tr>
</table>";
}
// disconnect from the database
mysql_close();
?>

try this code
<?php // connect to the database
$host = 'localhost';
$username = 'user';
$pass = 'password';
mysql_connect($host,$username,$pass);
mysql_select_db("myDB");
// select everything from the news table
$query = "SELECT * FROM `tablename`";
$result = mysql_query($query);
echo "<table>";
echo "<tr>";
while( ($row = mysql_fetch_array($result)))
{
echo "<td>".$row['movietitle']."</td>";
echo "<td>".$row['genre']."</td>";
echo "<td>".$row['LastViewed']."</td>";
echo "<td>".$row['Location']."</td>";
}
echo "</tr>";
echo "</table>";
// disconnect from the database
mysql_close();
?>

Related

basic multiple answers quiz system checkbox ambiguity

I am trying to build a basic quiz system and everything seems ok.
The following code shows how a users choose the correct answer and the getresult.php shows the result. In my database, there is a question, opt1, opt2, opt3 opt4 and answer column.
<form method="POST" action="getresult.php">
<label>Enter Your Name:</label><br>
<input type="text" name="name" required><br><br>
<?php
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("SELECT * FROM quiz");
$stmt->execute();
$result=$stmt->get_result();
while($myrow = $result->fetch_assoc())
{
echo "<form method='POST' action='getresult.php'>";
echo $myrow['id'];
echo ".";
echo $myrow['question'];
echo "<br>";
echo "<input type='checkbox' name='mycheck[]' value=".$myrow['opt1'].">";
echo $myrow['opt1'];
echo "<br>";
echo "<input type='checkbox' name='mycheck[]' value=".$myrow['opt2'].">";
echo $myrow['opt2'];
echo "<br>";
echo "<input type='checkbox' name='mycheck[]' value=".$myrow['opt3'].">";
echo $myrow['opt3'];
echo "<br>";
echo "<input type='checkbox' name='mycheck[]' value=".$myrow['opt4'].">";
echo $myrow['opt4'];
echo "<br><br>";
}
?>
<input type="submit" name="submit" value="Get Results" class="btn btn-primary">
getresult.php
<?php
extract($_POST);
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("SELECT * FROM quiz");
$stmt->execute();
$result=$stmt->get_result();
$myrow = $result->fetch_assoc();
$totalCheckboxChecked = sizeof($_POST['mycheck']);
$submit=isset($_POST['submit']);
$count=0;
if($submit)
{
for($i=0;$i<$totalCheckboxChecked;$i++)
{
if($mycheck[$i]==$myrow['answer'])
{
$count=$count+1;
}
}
echo "Hello ";
echo $_POST['name'];
echo "<br>";
echo "You scored ";
echo $count;
}
Now the problem is with the checkbox, I can check all the values from all the questions. And when I use radio button I can check only one value from all questions. How can I check only one value from one question.
I don't know why you're not using radio buttons if you plan to allow only one selection, but you can set a limit to have the same thing with checkboxes with some JavaScript (or jQuery).
Here is an example: see fiddle demo
var limit = 1;
$('input').on('change', function(event) { // this could've been a 'click' event too.
if($(this).siblings(':checked').length >= limit) {
this.checked = false;
/* OR you can do like:
if($("input[name='mycheck']:checked").length > limit) { //... }
*/
}
});
if the question contain only one answer better use radio buttons to select the option
or
else
use this jquery to select single value from checkbox
$('input[type="checkbox"]').on('change', function() {
$('input[type="checkbox"]').not(this).prop('checked', false);
});

Multiple search form using functions and if else

Hi Im creating a multiple search form using PHP,HTML,SQL with the use of functions, for example I have 3 search fields Firstname, lastname and email. I would let the user input from any of those, therefore i would be needing the if else statement, but to be able to satisfy all conditions it would take a lot of if else, so i think of using a function to output the table and place it inside the if else after the query on the database. But it seems that it could not be able to search in the database if I do it like this it outputs "0 results", but if i remove the function and place it on the end of my script I am able to search in the db but it could not detect my else condition which is "You have not yet entered any values"
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if (!empty($sfname) && empty($slname) && empty($semail) )
{
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%'" ;
checkres();
}
else if (!empty($sfname) && !empty($slname) && empty($semail))
{
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%' AND LastName LIKE '%". %slname. "%'";
checkres();
}
else
{
echo "You have not yet entered any values ";
}
mysqli_close($conn);
?>
This is the new one
<form method="post" action="#" id="searchform">
First Name:<br>
<input type="text" name="fname">
<br>Last Name:<br>
<input type="text" name="lname">
<br>Email: <br>
<input type="text" name="email">
<br>
<input type="submit" name="submit" value="Search">
</form>
<?php
$sfname = $_POST["fname"];
$slname = $_POST["lname"];
$semail = $_POST["email"];
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if(!empty($sfname) || !empty($slname) || !empty($semail)){
$emailQueryPart = !empty($semail) ? "Email LIKE '%$semail%'" : "";
$lastnameQueryPart = !empty($slname) ? "LastName LIKE '%$slname%'" : "";
$firstnameQueryPart = !empty($sfname) ? "FirstName LIKE '%$sfname%'" : "";
$arr = array($emailQueryPart, $lastnameQueryPart,$firstnameQueryPart);
$sql = "select * from Userlist";
for($i = 0; $i < count($arr); $i++){
if(!empty($arr[$i])){
if($i > 0){
$sql.= " AND ".$arr[$i];
}else{
$sql.= " WHERE ".$arr[$i];
}
}
}
}else{
echo "You must enter at least one value";
}
checkres();
mysqli_close($conn);
?>
You have a few errors:
$sql = "select * from Userlist where FirstName LIKE '%". $sfname ."%' AND LastName LIKE '%". %slname. "%'";
You have %slname instead of $slname.
Another mistake is in the program flow. Your else condition, which is saying :"You have not yet entered any values" will be reached in two cases:
When all fields are left blank
When all fields are filled with values.
You don't want that. You have to improve your logic, and build a query based on that, and that can be done like this:
function checkres()
{
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
if(!empty($sfname) || !empty($slname) || !empty($semail)){
$emailQueryPart = !empty($semail) ? "Email LIKE '$semail'" : "";
$lastnameQueryPart = !empty($slname) ? "LastName LIKE '%$slname%'" : "";
$firstnameQueryPart = !empty($sfname) ? "FirstName LIKE '%$sfname%'" : "";
$arr = array($emailQueryPart, $lastnameQueryPart,$firstnameQueryPart);
$sql = "select * from Userlist";
for($i = 0; $i < count($arr); $i++){
if(!empty($arr[$i])){
if($i > 0){
$sql.= " AND ".$arr[$i];
}else{
$sql.= " WHERE ".$arr[$i];
}
}
}
}else{
echo "You must enter at least one value";
}
checkres();
mysqli_close($conn);
?>
What you do is in my opinion a little bit confusing (and a little bit odd n terms of the program's flow structure).
You can simply use an array of variables for your input fields and then loop through the array to generate your SQL statement. So your HTML form would look like this:
<form method="post" action="#" id="searchform">
First Name:<br />
<input type="text" name="queryArray[FirstName]" />
<br />Last Name:<br />
<input type="text" name="queryArray[LastName]" />
<br />Email:<br />
<input type="text" name="queryArray[Email]" />
<br />
<input type="submit" name="submit" value="Search" />
</form>
A more clear structure would be if you define these 2 functions, which of course can be placed anywhere in your PHP code block:
function createSql($queryArray) {
if (is_array($queryArray)) {
$sql = null;
foreach ($queryArray as $key => $value) {
if ($value != null ) {
$addQuery = "`".$key."` LIKE '%".$value."%'";
if ($sql == null)
$sql = "SELECT * FROM `Userlist` WHERE ".$addQuery;
else
$sql = $sql." AND ".$addQuery;
}
return $sql;
}
}
function checkres($sql) {
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
die("Connection failed: " . mysqli_connect_error());
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0) {
//Headers
echo "<table border='1' style='width:100%'>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else
echo "0 results";
// Close connection
mysqli_close($conn);
}
Finally you will have to call the functions according to user activity:
if ($_POST != null) {
$sql = createSql($_POST[queryArray]);
checkres($sql);
}
An example how the SQL generation works is listed here

SQL insert query loop

Hello so i am doing this school assigment where i have make a comment system corresponding to the post ID and i know that it looping three times but i gave it the post id. And i know that the postID is changeing all the time. i just have no idea how to fix this bug any ideas?
<?php require_once("menu.php");
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
if (!empty($_POST['comment']) ) #To insert new comments in the database
{
$comment = $_POST['comment'];
$userid = $_SESSION['userID'];
$insertCommentQuery = "INSERT INTO `tblcomments` (`Content`,`UserID`,`PostID`,`Timestamp`) VALUES ('$comment','$userid','$postid',CURRENT_TIMESTAMP)";
$resultComment = mysqli_query($connection, $insertCommentQuery)
or die("Error in the query: ". mysqli_error($connection));
}
echo "<div class=\"wrapper\">";
echo "<div class=\"titlecontainer\">";
echo "<h1>$row[Title]</h1>";
echo "</div>";
echo "<div class=\"textcontainer\">";
echo "<span>$row[Content]</span>";
echo "</div>";
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>">
</div>
<?php
}
echo "<div class=\"timestampcontainer\">";
echo "<b>Date posted :</b>$row[TimeStamp] ";
echo "<b>Author :</b> Admin";
echo "</div>";
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
echo "<div class=\"commentcontainer\">";
echo "<div class=\"commentusername\"><h1>Username :$commentRow[Username]</h1></div>";
echo "<div class=\"commentcontent\">$commentRow[Content]</div>";
echo "<div class=\"commenttimestamp\">$commentRow[Timestamp]</div>";
echo "</div>";
}
if (!empty($_SESSION['userID']) )
{
echo "<form method=\"POST\" action=\"\" class=\"post-frm\">";
echo "<label>New Comment</label>";
echo "<textarea id=\"comment\" name=\"comment\"> </textarea>";
echo "<input id=\"submit\" type=\"submit\" name =\"submit\" class=\"button\"/>" ;
echo "</form>";
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Well, that's exactly what your script does. It queries all posts, loops through them, and then performs an insert for all of them. To fix this, store the id of the post in the comment form. When you post the form, insert just a single comment and use the id in the form.
That could look something like this:
<?php
if (array_key_exists('postid', $_POST))
{
$postid = $_POST['postid'];
$comment = $_POST['comment'];
// Perform a single insert here, and use $postid and $comment.
}
// Then, start rendering the page:
require_once(menu.php);
$connection = connectToMySQL();
$selectPostQuery = SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC;
$result = mysqli_query($connection,$selectPostQuery)
or die(Error in the query: . mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
// Render the post itself here.
?>
<div class="wrapper">;
<div class="titlecontainer">;
<h1><?=$row['Title']?></h1>;
</div>;
<div class="textcontainer">;
<span><?=$row['Content']?></span>;
</div>;
<?php
// Render a comment form for each post (is that what you did?)
if (!empty($_SESSION['userID']) )
{?>
<form method=POST action= class=post-frm>
<label>New Comment</label>
<textarea id=comment name=comment></textarea>
<input type=hidden name=postid value=<?=$postid?>/>
<input id=submit type=submit name =submit class=button/>
</form>
<?}
}
Most of your code is the same, only the processing of the post data is now done before the loop.
Otherwise, I just fixed some small syntactic things (and maybe introduced new ones, I haven't tested it).
Also, I took the HTML out of echoes. It's a matter of taste, of course, but experience has taught me that big chunks of HTML in echo statements isn't very readable or maintainable. Rather just close the PHP tags, output the raw HTML and echo only the variables in it. You can use the short notation for that: <?= $value ?>, which basically means <?php echo $value ?>.

Search Data not outputting the correct results

This form is a search form which allows the user to search for an event using the Venue and category fields which are scripted as dropdown boxes and the Price and event title as user input text boxes, as shown via the code if a keyword is entered which matches the fields on the database it should output all the related information for that event if any matches have been made on either search fields, the tickboxes allow the user to identify what criteria they would like to search with, if the tickbox field hasn't been checked then the SQL enquiry will not search for keywords with that corresponding field.
The issue is, it all seems to work fine except no results seem to show up for the Venue and Category fields if they was solely used to search for an event. But if I choose another field everything is outputting correctly including the venue and Category field.
DATABASE: http://i.imgur.com/d4uoXtE.jpg
HTML FORM
<form name="searchform" action ="PHP/searchfunction.php" method = "post" >
<h2>Event Search:</h2>
Use the Check Boxes to indicate which fields you watch to search with
<br /><br />
<h2>Search by Venue:</h2>
<?php
echo "<select name = 'venueName'>";
$queryresult2 = mysql_query($sql2) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult2)) {
echo "\n";
$venueID = $row['venueID'];
$venueName = $row['venueName'];
echo "<option value ='$venueName'";
echo ">$venueName</option>";
}# when the option selected matches the queryresult it will echo this
echo "</select>";
echo" <input type='checkbox' name='S_venueName'>";
mysql_free_result($queryresult2);
mysql_close($conn);
?>
<br /><br />
<h2>Search by Category:</h2>
<?php
include 'PHP/database_conn.php';
$sql3 ="SELECT catID, catDesc
FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysql_query($sql3) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult3)) {
echo "\n";
$catID = $row['catID'];
$catDesc = $row['catDesc'];
echo "<option value = '$catDesc'";
echo ">$catDesc </option>";
}
echo "</select>";
mysql_free_result($queryresult3);
mysql_close($conn);
?>
<input type="checkbox" name="S_catDes">
<br /><br />
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br /><br />
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br /><br />
<input name="update" type="submit" id="update" value="Search">
</form>
PHP CODE THAT DEALS WITH PROCESSING THE FORM DATA
<?php
include 'database_conn.php';
$venuename = $_POST['venueName']; //this is an integer
$catdesc = $_POST['catdesc']; //this is a string
$Price = $_POST['S_price'];
$EventT = $_POST['S_EventT'];
#the IF statements state if the tickbox is checked then search with these enquires
if (isset($_POST['S_VenueName'])) {
$sql = "SELECT * FROM te_venue WHERE venueName= '$venuename'";
}
if (isset($_POST['S_catDes'])) {
$sql = "SELECT * FROM te_category WHERE catID= '$catdesc'";
}
if (isset($_POST['S_CheckPrice'])) {
$sql = "SELECT * FROM te_events WHERE (eventPrice LIKE '%$Price%')";
}
if (isset($_POST['S_EventTitle'])) {
$sql = "SELECT * FROM te_events WHERE (eventTitle LIKE '%$EventT%')";
}
$queryresult = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult))
{
echo "Event Title: "; echo $row['eventTitle'];
echo "<br />";
echo "Event Description: "; echo $row['eventDescription'];
echo "<br />";
echo "Event Venue "; echo "$venuename";
echo "<br />";
echo "Event Category "; echo "$catdesc";
echo "<br />";
echo "Event Start Date "; echo $row['eventStartDate'];
echo "<br />";
echo "Event End Date "; echo $row['eventEndDate'];
echo "<br />";
echo "Event Price "; echo $row['eventPrice'];
echo "<br /><br />";
}
mysql_free_result($queryresult);
mysql_close($conn);
?>
Try using atleast MySQLi instead of deprecated MySQL. You can try this:
database_conn.php:
<?php
/* ESTABLISH YOUR CONNECTION. REPLACE THE NECESSARY DATA BELOW */
$con=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
HTML Form:
<html>
<body>
<?php
include 'PHP/database_conn.php';
$sql2="SELECT venueID, venueName FROM te_venue"; /* PLEASE REPLACE THE NECESSARY DATA */
echo "<select name = 'venueName'>";
$queryresult2 = mysqli_query($con,$sql2);
while($row = mysqli_fetch_array($queryresult2)) {
echo "\n";
$venueID = mysqli_real_escape_string($con,$row['venueID']);
$venueName = mysqli_real_escape_string($con,$row['venueName']);
echo "<option value ='$venueName'>";
echo $venueName."</option>";
} /* when the option selected matches the queryresult it will echo this ?? */
echo "</select>";
echo "<input type='checkbox' name='S_venueName'>";
?>
<br><br>
<h2>Search by Category:</h2>
<?php
$sql3 ="SELECT catID, catDesc FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysqli_query($con,$sql3);
while($row = mysqli_fetch_array($queryresult3)) {
echo "\n";
$catID = mysqli_real_escape_string($con,$row['catID']);
$catDesc = mysqli_real_escape_string($con,$row['catDesc']);
echo "<option value = '$catDesc'>";
echo $catDesc."</option>";
}
echo "</select>";
?>
<input type="checkbox" name="S_catDes">
<br><br>
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br><br>
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br><br>
<input name="update" type="submit" id="update" value="Search">
</form>
</body>
</html>
PHP:
<?php
include 'database_conn.php';
$venuename = mysqli_real_escape_string($con,$_POST['venueName']); /* this is an integer */
$catdesc = mysqli_real_escape_string($con,$_POST['catdesc']); /* this is a string */
$Price = mysqli_real_escape_string($con,$_POST['S_price']);
$EventT = mysqli_real_escape_string($con,$_POST['S_EventT']);
/* SHOULD PRACTICE USING ESCAPE_STRING TO PREVENT SOME OF SQL INJECTIONS */
/* the IF statements state if the tickbox is checked then search with these enquires */
if (isset($_POST['S_VenueName'])) {
$sql = "SELECT * FROM te_venue WHERE venueName= '$venuename'";
}
if (isset($_POST['S_catDes'])) {
$sql = "SELECT * FROM te_category WHERE catID= '$catdesc'";
}
if (isset($_POST['S_CheckPrice'])) {
$sql = "SELECT * FROM te_events WHERE (eventPrice LIKE '%$Price%')";
}
if (isset($_POST['S_EventTitle'])) {
$sql = "SELECT * FROM te_events WHERE (eventTitle LIKE '%$EventT%')";
}
$queryresult = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($queryresult))
{
echo "Event Title: "; echo $row['eventTitle'];
echo "<br />";
echo "Event Description: "; echo $row['eventDescription'];
echo "<br />";
echo "Event Venue "; echo "$venuename";
echo "<br />";
echo "Event Category "; echo "$catdesc";
echo "<br />";
echo "Event Start Date "; echo $row['eventStartDate'];
echo "<br />";
echo "Event End Date "; echo $row['eventEndDate'];
echo "<br />";
echo "Event Price "; echo $row['eventPrice'];
echo "<br /><br />";
}
mysqli_close($conn);
?>
What if user checks all the check box? What would happen is, the last condition will be used. The first three conditions will be overwritten by the last condition.
If you use ELSE IF in those conditions, the first condition will be implemented.
My advice is to use radio button instead of check box and hope you gets the idea along the way.
Have you tried printing out your $sql query for debugging?
Try <input type="checkbox" name="S_catDes" value="checked">.
From memory checkboxes need a value field but I could be wrong. Hope this helps.

Only updating last database record - Array required?

Could someone help me out, I am only new to PHP and SQL. I have created a database, and want to update it using a form on a HTML page. It all works fine except it only updates the last record. I presume this is because I need an array but am unsure how to do this. WOuld anyone have some good examples or point me in the right direction?
The code is as follows:
Display Page
<?php
$con=mysqli_connect("xx","xx","xx","xx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM webquestion");
if ($result) {
// create a new form and then put the results
// into a table.
echo "<form method='post' action='delete.php' >";
echo "<table class='webquestion' >
<tr>
<th width='12%'>Department</th>
<th width='15%'>Name</th>
<th width='25%'>E-mail</th>
<th width='20%'>Message</th>
<th width='20%'>Notes</th>
<th width='8%'>Delete</th>
</tr>";
while ($row = $result->fetch_object()) {
$department = $row->department;
$name = $row->name;
$email = $row->email;
$message = $row->message;
$notes = $row->notes;
$id = $row->id;
//put each record into a new table row with a checkbox
echo "<tr>
<td>$department</td>
<td>$name</td>
<td>$email</td>
<td>$message</td>
<td><input type='text' name='notes' id='notes' value='$notes' />
<td><input type='checkbox' name='checkbox[]' id='checkbox[]' value=$id />
<td><input type='hidden' name='id' value=$id />
</tr>";
}
// when the loop is complete, close off the list.
echo "</table><p><input id='delete' type='submit' class='button' name='delete' value='Delete Selected Items' style='float:left'/>
</table><p><input id='update' type='submit' class='button' name='update' value='Update' style='float:left'/></p>
</form>
<form action='showContactUs.php' >
<input type='submit' value='Refresh Records' style='float:left'>
</form>";
}
?>
PHP Code
<?php
if(isset($_POST['update'])) // from button name="update"
$hostname = 'xx';
$username = 'xx';
$password = 'xx';
$dbname = 'xx';
/*** create a new mysqli object with default database***/
$mysqli = #new mysqli($hostname, $username, $password, $dbname);
/* check connection */
if(!mysqli_connect_errno())
{
/*** if we are successful ***/
echo 'Connected Successfully<br />';
/*** sql to UPDATE an existing record ***/
$notes = $_POST['notes'];
$sql = "UPDATE webquestion
SET notes = '$notes'
WHERE id = '$id'";
/*** execute the query ***/
if($mysqli->query($sql) === TRUE)
{
echo mysqli_affected_rows($mysqli). ' Records UPDATED successfully<br />';
}
else
{
echo 'Unable to UPDATE Records: '.$sql.'<br />' . $mysqli->error;
}
/*** close connection ***/
$mysqli->close();
}
else
{
/*** if we are unable to connect ***/
echo 'Unable to connect';
exit();
}
?>
Thanks for your help.
To pass an array via POST simply add a '[]' to the name atribute:
<td><input type='text' name='notes[]' id='notes' value='$notes' />
<td><input type='hidden' name='id[]' value=$id />
Then on the server side you would do:
$notes = $_POST['notes']; //notes array
foreach($_POST['id'] as $index=>$id) //traverse the ids array
{
$note = $notes[$index]; //Get the note on the same row as id
/*** sql to UPDATE an existing record ***/
$sql = "UPDATE webquestion SET notes = '$note' WHERE id = '$id'";
/*** execute the query ***/
if($mysqli->query($sql) === TRUE)
{
echo mysqli_affected_rows($mysqli). ' Records UPDATED successfully<br />';
}
else
{
echo 'Unable to UPDATE Records: '.$sql.'<br />' . $mysqli->error;
}
}
If you want to update several rows at the same time by matching with their IDs, you need an array of IDs:
array(25,33,26,24)
or any other type of array.
Then you should loop through your array and update the db accordingly:
for($i=0; $i < count($id_array); $i++)
{
$id = $id_array[$i];
$sql = "UPDATE webquestion
SET notes = '$notes'
WHERE id = '$id'";
// and the rest of SQL update
}

Categories