I have a simple form in PHP, having 4 check boxes. The user can select 0-4 number of checkboxes and based on their selection the results should differ.
Basically the four checkboxes represents the four campuses of a university- Campus A,B,C,D. and suppose if the user select 2 campuses say A and C. then I want to query the database based on the selection and retrieve the courses corresponding to those two campuses A and C. If the user selects only one campus then I want to retrieve courses in that single campus.
On mySQL, I have a Location table with the following schema (ID,Campus Name, City, State) with ID being the primary key. Also I have a course table with schema as Course(ID,CourseName,LocationID,Seatsleft). ID is the primary key and LocationID is the foreign key, which references ID of Location table.
My PHP code is as follows:
Here is the updated version of my code.
PHP form check box selecting different campuses
<body>
<?php
require 'connection.php';
if(isset($_POST['formSubmit']))
{
$aCampus = $_POST['campus'];
if(empty($aCampus))
{
echo("<p>You didn't select any campus.</p>\n");
}
else
{
$N = count($aCampus);
echo("<p>You selected $N campus(s): ");
for($i=0; $i < $N; $i++)
{
echo($aCampus[$i] . " ");
}
echo("</p>");
}
}
function IsChecked($chkname,$value)
{
if(!empty($_POST[$chkname]))
{
foreach($_POST[$chkname] as $chkval)
{
if($chkval == $value)
{
return true;
}
}
}
return false;
}
$where="1";
if(!empty($_POST['campus'])){
foreach ($_POST['campus'] as $campus){
$where=" LocationID='". $campus."'";
}
}
//$query = "SELECT `Name` FROM `course` WHERE LocationID=1";
$query="SELECT `Name` FROM `course` WHERE 1 AND (".$where.")";
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$coursename =$query_row['Name'];
echo $coursename. '<br/>';
}
} else {
echo mysql_error();
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>
Which campus courses do you want to get access to?<br/>
<input type="checkbox" name="campus[]" value=1 />Campus A<br />
<input type="checkbox" name="campus[]" value=2 />Campus B<br />
<input type="checkbox" name="campus[]" value=3 />Campus C<br />
<input type="checkbox" name="campus[]" value=4 />Campus D
</p>
<input type="submit" name="formSubmit" value="Submit" />
</form>
</body>
</html>
My question is how do I take options from my PHP form and query the database to retrieve courses from the selected campuses only?
Please try with following simple query creator logic.
$whereArr =Array();
$whereArr[] = 1;
if(!empty($_POST['campus'])){
foreach ($_POST['campus'] as $campus){
$whereArr[]=" LocationID LIKE ',". $campus.",'";
}
}
$query="SELECT `Name` FROM `course` WHERE 1 AND(".implode(" OR ",$whereArr)." )";
Above code will work for following record:
289,"Math","2,3,",67
In this instance I would store the campuses as a comma delimited string in the database. Then you can use the FIND_IN_SET() function in mySQL to query based on that
for instance
a record for the course
203,"Biology","1,2,4",34
then you can
SELECT * FROM course WHERE FIND_IN_SET(4,locationid)
which will give you all of the records that have 4 in the "set"
Something like this :
$validoptions = array('A','B','C','D');
$allvalid = true;
foreach ($_POST['campus'] as $campus){
if (!in_array($campus,$validoptions)) $allvalid = false;
}
if (!$allvalid) {
echo 'Wrong campuses selected. Try again.';
exit;
}
$query = 'SELECT * FROM `Courses` WHERE ';
$query .= 'LocationID = \''.implode('\' OR LocationID = \'',$campuses).'\'';
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) die('Could not connect: ' . mysql_error());
mysql_select_db("databasename");
$res = mysql_query($query);
$data = array();
if ($res && mysql_num_rows()) {
$data = array();
while($d = mysql_fetch_array($res)) {
$data[] = $d;
}
}
if (count($data) > 0) {
echo 'No courses found !';
}else {
echo 'Courses found : ';
print_r($data);
}
Related
I have a little problem in php.
problem is that i want to search MySQL table by php coding.
In php i want to use Drop down menu And a text field.
I have two MySQL table name is category and products, now i use category entries
in drop-down menu (by cat_name).and in the search text area
i want write any product name selecting by cat_name from drop down menu and then click on search button. Then it will show me the result from product table in table format.
Can any one help me
Thanks.
i have tow category: Mobile and Laptop in categories table and
i have many products name: Dell, Hp, Toshiba, Samsung, Iphone etc...in products table
1. categories
cat_id
cat_name
2. products
product_id
product_cat
product_name
product_price
I have php code. this working correct till populate cat_name from database in drop-down.
result.php
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("ecomerce");
$sql = mysql_query('SELECT cat_name FROM categories ORDER BY cat_name');
$models = array();
while ($row = mysql_fetch_array($sql)){
$models[] = $row;
}
?>
<form action="search.php" method="post">
<select name="term">
<?php
foreach ($models as $model) {
?>
<option value="<?php echo $model['cat_name']?>"><?php echo $model['cat_name']?></option>
<?php
}
?>
</select>
<form >
<input type="text" class="form-control" placeholder="Search a Product">
<input type="submit" name="submit" value="Search" />
</form>
search.php
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("ecomerce");
if(isset($_POST['term']) {
$term = $_POST['term'];
$query = "SELECT * FROM products WHERE product_cat = '".mysql_escape_string($term)."'";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result) {
// display results
echo 'Product ID '.$row['product_id'];
echo 'product_title: '.$row['product_name'];
echo 'product_price: '.$row['product_price'];
}
}
?>
config.php
<?php
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_USER', 'DB_Username');
DEFINE ('DB_PASSWORD', 'DB_Password');
DEFINE ('DB_NAME', 'Database_Table_Name');
DEFINE ('DBCONN', 'Path/to/dbconnect.php');
?>
dbconnect.php
<?php
$dbconn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
IF (!$dbconn) {
die('Could not connect: ' . mysql_error());
}
IF (!mysql_select_db (DB_NAME)) { die('Could not select table: ' . mysql_error()); }
?>
functions.php
<?php
// Categories
Function Categories($mysql = true) {
$result = array();
IF ($mysql == true) { require(DBCONN); }ELSE{ global $dbconn; } // db connection
// query cats to array
$sql = mysql_query("SELECT cat_name FROM categories ORDER BY cat_name");
while ($row = mysql_fetch_array($sql)){
$result[] = stripslashes($row['cat_name']);
}
mysql_free_result($sql);
IF ($mysql == true) { mysql_close($dbconn); } // close connection
return $result;
}
// Category dropdown
Function ddform_Categories($cats, $post = NULL) {
$result = "";
// set default
IF ((empty($post)) || ($post == "xx")) {
$result .="<option selected value=\"xx\">Choose Category</option>";
}ELSE{
$result .="<option value=\"xx\">Choose Category</option>";
}
foreach ($cats as $category) {
IF ($post == $category) {
$result .="<option selected value=\"".$category."\">".$category."</option>";
}ELSE{
$result .="<option value=\"".$category."\">".$category."</option>";
}
}
return $result;
}
// MySQL Search
Function CategorySearch($mysql = true, $cats, $post) {
$result = "";
$rows = "";
IF ($mysql == true) { require(DBCONN); }ELSE{ global $dbconn; } // db connection
$term = mysql_escape_string($post);
$query = "SELECT * FROM products WHERE product_cat = '$term'";
$sql = mysql_query($query);
IF (mysql_num_rows($sql)) {
while($r = mysql_fetch_array($sql) {
$rows .= "<tr><td>".$r['product_name']."</td><td>$".number_format($r['product_price'])."</td></tr>";
}
mysql_free_result($sql);
}ELSE{
$result = "<p>No Results</p>";
#$result .= "<p>SQL:\n".$query ."</p>"; // debug
}
IF ($mysql == true) { mysql_close($dbconn); } // close connection
IF (!empty($rows)) {
$result = "<table>".$rows."</table>";
}
return $result;
}
?>
Search.php
<?php
Require('config.php');
Include('functions.php')
$cats = Categories();
$post = "xx"; // default post value
IF (isset($_POST['Search'])) {
$post = htmlspecialchars(strip_tags(trim($_POST['term'])));
// build query
IF ( (!empty($post)) && (in_array($post, $cats)) ) {
$result = CategorySearch(true, $post);
}ELSE{
$result = "<p>Search option (".$post.") was invalid.</p>";
}
echo($result);
}
?>
<form action="search.php" name="search" method="post">
<select name="term"><?php echo(ddform_Categories($cats, $post))); ?></select>
<input type="text" class="form-control" placeholder="Search a Product">
<input type="submit" name="Search" value="Search" />
</form>
I'm working on a project where a user can click on an item. If the user clicked at it before , then when he tries to click at it again it shouldn't work or INSERT value on the DB. When I click the first item(I'm displaying the items straight from database by id) it inserts into DB and then when I click at it again it works(gives me the error code) doesn't insert into DB. All other items when I click at them , even if I click for the second, third, fourth time all of it inserts into DB. Please help guys. Thanks
<?php
session_start();
$date = date("Y-m-d H:i:s");
include("php/connect.php");
$query = "SELECT * FROM test ORDER BY `id` ASC LIMIT 3";
$result = mysql_query($query);
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$submit = mysql_real_escape_string($_POST["submit"]);
$tests = $_POST["test"];
// If the user submitted the form.
// Do the updating on the database.
if (!empty($submit)) {
if (count($tests) > 0) {
foreach ($tests as $test_id => $test_value) {
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
if ($match == $test_id) {
echo "You have already bet.";
} else {
switch ($test_value) {
case 1:
mysql_query("UPDATE test SET win = win + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 'X':
mysql_query("UPDATE test SET draw = draw + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 2:
mysql_query("UPDATE test SET lose = lose + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
default:
}
}
}
}
}
echo "<h2>Seria A</h2><hr/>
<br/>Welcome,".$username."! <a href='php/logout.php'><b>LogOut</b></a><br/>";
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
echo "<br/>",$id,") " ,$home, " - ", $away;
echo "
<form action='seria.php' method='post'>
<select name='test[$id]'>
<option value=\"\">Parashiko</option>
<option value='1'>1</option>
<option value='X'>X</option>
<option value='2'>2</option>
</select>
<input type='submit' name='submit' value='Submit'/>
<br/>
</form>
<br/>";
echo "Totali ", $sum = $win+$lose+$draw, "<br/><hr/>";
}
} else {
$error = "<div id='hello'>Duhet te besh Log In qe te vendosesh parashikime ndeshjesh<br/><a href='php/login.php'>Kycu Ketu</a></div>";
}
?>
Your problem is here :
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
You are not checking it correctly. You have to check if the entry in match_select exists for the user_id and the match_id concerned. Otherwise, $match would always be equal to the match_id field of the last inserted row in your database :
$match = "SELECT *
FROM `match_select`
WHERE `user_id` = '<your_id>'
AND `match_id` = '$test_id'";
$matchResult = mysql_query($match)or die(mysql_error());
if(mysql_num_rows($matchResult)) {
echo "You have already bet.";
}
By the way, consider using PDO or mysqli for manipulating database. mysql_ functions are deprecated :
http://www.php.net/manual/fr/function.mysql-query.php
validate insertion of record by looking up on the table if the data already exists.
Simplest way for example is to
$query = "SELECT * FROM match_select WHERE user_id = '$user_id'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// do not insert
}
else
{
// do something here..
}
In your form you have <select name='test[$id]'> (one for each item), then when you submit the form you are getting $tests = $_POST["test"]; You don't need to specify the index in the form and can simply do <select name='test[]'>, you can eventually add a hidden field with the id with <input type="hidden" value="$id"/>. The second part is the verification wich is not good at the moment; you can simply check if the itemalready exist in the database with a query
Here is revised code. Still no luck ! pls. help
<html>
<body>
<?php
$mysqli = new mysqli("localhost", "root", "password", "test");
$whereClauses = '';
$numLocations = count($_POST['Locations']);
$numJobs = count($_POST['Jobs']);
$i = 0;
if (! empty($_POST['Locations'])) {
foreach ($_POST['locations'] as $location) {
$whereClauses .="Locations='".mysql_real_escape_string($location)."'";
if ($i++ == $numLocations) {
$whereClauses .= " AND";
}
}
}
if (! empty($_POST['Jobs'])) {
foreach ($_POST['Jobs'] as $job) {
$whereClauses .="Jobs='".mysql_real_escape_string($job)."'";
}
if ($i++ == $numJobs) {
$whereClauses .= " AND";
}
}
$sql = "SELECT * FROM mytable '".$whereClauses."' ORDER BY id DESC '".$limit."'";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo $row['Locations'];
echo $row['Jobs'];
}
?>
</body>
</html>
===============================================
I created a HTML and PHP file to filter web form data based on multiple drop down filters. Here goes the form. When I run the form and PHP, I don't see any results in the browser. There is no error either. I'm working on an example posted by another forum member.
Please help. Thanks in advance.
<form action="showJobs_new.php" method="post">
<select name="Locations">
<option value="" selected="selected">All Locations</option>
<option value="arizona">Arizona</option>
<option value="alaska">Alaska</option>
</select>
<select name="Jobs">
<option value="" selected="selected">All jobs</option>
<option value="Carpenter">Carpenters</option>
<option value="Plumbers">Plumbers</option>
</select>
<input type="submit" value="search jobs" />
</form>
showJobs_new.php:
<html>
<body>
<?php
$username="root";
$password="password";
$database="test";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$whereClauses = array();
if (! empty($_POST['Locations'])) $whereClauses[] ="Locations='".mysql_real_escape_string($_POST['Locations'])."'";
if (! empty($_POST['Jobs'])) $whereClauses[] ="Jobs='".mysql_real_escape_string($_POST['Jobs'])."'";
$where = '';
if (count($whereClauses) > 0) { $where = ' WHERE '.implode(' AND ',$whereClauses); }
$sql = mysql_query("SELECT * FROM mytable ORDER BY id DESC $limit" .$where);
$result=mysql_query($sql);
or die("Error: ".mysql_error()."<br />Query: ".$sql);
while ($row = mysql_fetch_assoc($result)) {
echo $row['Locations'];
echo $row['Jobs'];
}
?>
</body>
</html>
Change the query to
$sql = mysql_query("SELECT * FROM mytable " .$where." ORDER BY id DESC $limit");
The order of the query seems to be wrong.
Hi dear You have two errors in query.
1-this is because you are putting wrong clause order. You need to learn what is the priority of clauses in query. When you run query, order of clause should look like
Select
From
Where
Group by
Having
Order BY
Limit
2- using mysql_query two times as suggested by user1599669
So your query should looks like
$sql = mysql_query("SELECT * FROM mytable $where ORDER BY id DESC $limit");
For more reference read from mysql dev.
i have a php form with text box,radiobutton and checkboxes.I have connected it to the databse , the values are getting stored into the database except the checkbox values.I want to enter all the checkbox values into the database.I want an backend such that it links to two tables.the text box and the radio button values are to be stored in the first table and the id's of the selected checkbox values in the other table.
u can store only that value in database which is checked, but you can not store all value of check box with same name attribute, because by checking that checkbox, that value is proceed to next page via POST/GET
but if u want all value of check box ( multiple check box) then use name array like below
<form action="checkbox.php" method="post">
<input type="checkbox" name="checkbox[]" value="a">
<input type="checkbox" name="checkbox[]" value="b">
<input type="checkbox" name="checkbox[]" value="c">
<input type="checkbox" name="checkbox[]" value="d">
<br>
<br>
<input type="submit" name="Submit" value="Submit">
</form>
<?
/* and in your checkbox.php you do this: */
if(isset($_POST['Submit']))
{
for ($i=0; $i<count($_POST['checkbox']);$i++) {
echo "<br />value $i = ".$_POST['checkbox'][$i];
}
}
?>
a connection table can be created (i.e A single php page connection is given to two tables of the same database)the code ia as follows. this code should be given as backend to the php page.
$dbhost = "localhost:3306"; // usually is localhost, but if not sure, check with your hosting company, if you are with webune leave as localhost
$dbuser = "root"; // change to your database password
$dbpass = "mysql"; // change to your database password
$dbname = "probe_config"; // provide your database name
$db_table = "mapping"; // leave this as is
$conn = mysql_connect("$dbhost", "$dbuser", "$dbpass");
$select = mysql_select_db("$dbname");
//selecting the urls
$selected = $_POST['urlSelect'];
if (count($selected) > 0)
{
for ($i=0;$i<count($selected);$i++) {
echo "$selected[$i] <br />";
}
}
$timeout=$_POST['timeout'] ;
$wait=$_POST['wait'];
$clearcache=$_POST['clearcache'];
$name=$_POST['name'];
$replication=$_POST['replication'];
//inserting into the databse
$query = "INSERT INTO webmeasurementsuite (wait, timeout, clearcache, name, replication)
values ($wait, $timeout, '$clearcache', '$name', $replication)";
if (!mysql_query($query,$conn))
{
die('Error: ' . mysql_error());
}
else
{
echo "1 record added to WMS";
$query = "SELECT wms_id FROM webmeasurementsuite ORDER BY wms_id DESC LIMIT 1";
if (!($result=mysql_query($query,$conn)))
{
die('Error: ' . mysql_error());
}
else
{
$row = mysql_fetch_assoc($result);
$id=$row['wms_id'];
$selected = $_POST['urlSelect'];
if (count($selected) > 0)
{
for ($i=0;$i<count($selected);$i++) {
$urlentry=$urlentry.", ";
if($i==0)
{
$urlentry="";
$j++;
}
$urlentry=$urlentry .$selected[$i];
}
}
echo $urlentry;
echo '<br />id='.$id;
//insert for the second table
$query= "INSERT INTO mapping(wms_Id, wm_Id) values ($id, '$urlentry')";
if (!mysql_query($query,$conn))
{
die('Error: ' . mysql_error());
}
else
{
echo "Mapping Done";
}
}
}
mysql_close($conn);
?>
I'm having trouble inserting data into a table.
I have the following tables: track (id, tracktitle), album (id, albumtitle), composer (id, composername), albumtrack (PRIMARY: trackid, albumid, composerid).
My PHP page allows you to add a track and then select the album and composer connected with it. It adds the track to the tracktable okay but it won't add it to an album.
I keep looking around for how to do it and I keep getting a bit lost.
Can anyone tell me how I should be correctly doing this?
Thanks
if (isset($_POST['tracktitle'])):
// A new track has been entered
// using the form.
$cid= $_POST['cid'];
$tracktitle = $_POST['tracktitle'];
$albs = $_POST['albs'];
if ($cid == '') {
exit('<p>You must choose an composer for this track. Click "Back" and try again.</p>'); }
$sql = "INSERT INTO track, albumtrack SET
track.tracktitle='$tracktitle', albumtrack.albumid='$albs', albumtrack.composerid='$cid' " ;
if (#mysql_query($sql)) {
echo '<p>New track added</p>';
} else {
exit('<p>Error adding new track' . mysql_error() . '</p>');
}
$trackid = mysql_insert_id();
if (isset($_POST['albs'])) {
$albs = $_POST['albs'];
} else {
$albs = array();
}
$numAlbs = 0;
foreach ($albs as $albID) {
$sql = "INSERT IGNORE INTO albumtrack
SET albumtrack.trackid='$trackid', albumtrack.albumid='$albs', albumtrack.composerid='$cid'";
if ($ok) {
$numAlbs = $numAlbs + 1;
} else {
echo "<p>Error inserting track into album $albID: " .
mysql_error() . '</p>';
}
}
?>
<p>Track was added to <?php echo $numAlbs; ?> albums.</p>
<p>Add another track</p>
<p>Return to track search</p>
<?php
else: // Allow the user to enter a new track
$composers = #mysql_query('SELECT id, composername FROM composer');
if (!$composers) {
exit('<p>Unable to obtain composer list from the database.</p>');
}
$albs = #mysql_query('SELECT id, albumtitle FROM album');
if (!$albs) {
exit('<p>Unable to obtain album list from the database.</p>');
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>Enter the new track:<br />
<textarea name="tracktitle" rows="1" cols="20">
</textarea></p>
<p>Composer:
<select name="cid" size="1">
<option selected value="">Select One</option>
<option value="">---------</option>
<?php
while ($composer= mysql_fetch_array($composers)) {
$cid = $composer['id'];
$cname = htmlspecialchars($composer['composername']);
echo "<option value='$cid'>$cname</option>\n";
}
?>
</select></p>
<p>Place in albums:<br />
<?php
while ($alb = mysql_fetch_array($albs)) {
$aid = $alb['id'];
$aname = htmlspecialchars($alb['albumtitle']);
echo "<label><input type='checkbox' name='albs[]' value='$aid' />$aname</label><br />\n";
}
?>
Your insert sentence is wrong:
Try this:
$sql = "INSERT IGNORE INTO albumtrack (trackid, albumid, composerid) values " .
"($trackid, $albs, $cid)";
Assuming your IDs are numeric.
Beware of SQL Injections when you inject non-sanitized values you get from your request.
Beside's Pablo's corrected way of writing the query. I also notice you are trying to insert into two tables at once with:
$sql= "INSERT INTO track, albumtrack"
MySQL does not allow inserting into two tables at once.