Please can anyone help me with this?
I have 2 tables, location and tickets and what I have built so far is a form in a div that users enter the name of the city or town where they would like to see a live music performance. This form is submitted and an SQL statement is passed querying the location table. In another div, the users search query appears in a box on the screen. What I would like to do next is to write an SQL statement that will lookup the user's query and dynamically display the relevant ticket information from the ticket table based on the location ID.
For example, the user types in 'Newcastle' as their search query, the location table finds the city of Newcastle and displays the user's result in a div called 'tickets'..I would like to display all the fields that correspond with 'Newcastle' from the ticket table.
The locationID is the primary key in the location table and has 3 other column, city, town and postcode.
The ticket table consists of ticketID being the primary key, the locationID being the foreign Key and the other fields i.e venue, tPrice, date and time. I think the problem im having is im not passing through the variable from the users query so that the ticket table can look it up and display the relevant information.
Here is the code for the form:
<div id="search">
<form name="searchForm" id="searchForm" class="searchForm" method="post">
<input type="text" name="citySearch" id="citySearch" class="citySearch" placeholder="Enter name city/town..." autofocus="autofocus" />
<input type="submit" name="ticketSearch" id="ticketSearch" class="ticketSearch" value="Search" />
</form>
</div>
Here is the code to display the user's query:
<div id="locationResult">
<?php
include( 'classes/database_connection.php' );
$cSearch = $_POST['citySearch'];
$sql = "SELECT DISTINCT city FROM location WHERE city = '$cSearch'";
mysql_query($sql) or die (mysql_error());
$queryresult = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($queryresult)) {
$city = $row['city'];
echo $row["city"];
}
mysql_free_result($queryresult);
mysql_free_result($qResult);
mysql_close($conn);
?>
</div>
</div>
This is where I want to display the ticket results from the ticket table:
<div id="ticketsResults">
<table class="ticketResult" border="0" cellspacing="5">
<tr>
<td><b>Venue</b></td>
<td><b>Price</b></td>
<td><b>Date</b></td>
<td><b>Time</b></td>
<td><b>Street View</b></td>
</tr>
<?php
include( 'classes/database_connection.php' );
$locID = $_POST['locationID'];
$citySearch = $_POST['citySearch'];
$sQL = "SELECT locationID FROM location";
//Here is where I want it to display dynamic information rather than manually type the location
$ticketSQL = "SELECT * FROM ticket NATURAL JOIN location WHERE city = 'Newcastle' ";
mysql_query($sQL) or die (mysql_error());
$qResult = mysql_query($sQL) or die(mysql_error());
mysql_query($ticketSQL) or die (mysql_error());
$result = mysql_query($ticketSQL) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
// $ticketID = $row['ticketID'];
$venue = $row['venue'];
$ticketPrice = $row['tPrice'];
$date = $row['date'];
$time= $row['time'];
echo "<tr>\n";
echo "<td>$venue</td>\n";
echo "<td>£$ticketPrice</td>\n";
echo "<td>$date</td>\n";
echo "<td>$time</td>\n";
echo "<td>Click to see</td>\n";
echo "</tr>\n";
}
mysql_free_result($qResult);
mysql_free_result($result);
mysql_close($conn);
?>
</table>
</div>
So basically, I'm wanting an SQL statement that dynamically displays the tickets according to the user's query. Sorry about the copious amount of code! Any help given is greatly appreciated.
Before you do anything else I think you should work on your coding style, specifically your indentation. A quick google search should do the trick. Next look into mysql prepared statements because currently your code is unsafe. Like jordanm said, it is subject to SQL injection.
For example, if someone entered blah' OR 'x'='x as a city name. Your query would become
SELECT DISTINCT city FROM location WHERE city = 'blah' OR 'x'='x';
Basically it allows the user to do naughty things with your query, and you don't want that.
Below is a sample of how you can avoid this using mysql prepared statements:
// basic quick raw example
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$stmt = $mysqli->prepare('SELECT DISTINCT city FROM location WHERE city = ?');
$stmt->bind_param('s',$city_name);
$stmt->execute();
$stmt->bind_result($city);
while ($stmt->fetch())
{
echo $city;
}
That's all I'm going to leave you with because I feel like to answer the actual question (?) I will need to write the code for you. Goodluck
Related
I'm making a web site for a business and in the "car list" I would like to take information from 2 tables of my data base, one for the car info (name, price...) and the other one for the images URL table.
Example of my code:
$mysqli = new mysqli("localhost","root","","database") or die("1");
$sql = "SELECT * FROM cars WHERE type= '".$cartype."'";
$result = $mysqli->query($sql);
if($result)
{
while($row = $result->fetch_assoc())
{
?>
<table>
<tr>
<td> HERE IMAGE URL FROM TABLE 2 </td>
<td> <?php echo $row['name']; ?> INFO FROM TABLE 1 </td>
</td>
</table>
<?php
}
}
How can I connect to table 2 and put the info in my while loop?
Thanks a lot.
You are going to have to join your two database tables in your select query. To do that you need an id in your photos table that links it to your cars table.
Example:
$sql = "SELECT name,url FROM cars,photos WHERE cars.id = photos.car_id AND type= '".$cartype."'";
Then use
$row['name']; $row['url'];
Depending on the input from checkboxes I'm trying to echo out users in a database based on category in a table linking the users-table with categories. But I only get one result for each category, even though I know there are several users in each category.
I have spent several dies seaching for the correct way to do this, and based upon the many tutoriels and articles out there I thought this method would work. But it does not.
This is the code that doesn't do what I want it to do:
function printusers($idcheck, $cat){
$sqlString = "SELECT userid FROM user_category WHERE categoryid ='$idcheck'";
$result = mysqli_query($dbLink, $sqlString) or die("Could not search for user id.." . mysqli_error($dbLink));
$row = mysqli_fetch_assoc($result);
// Make the first user on the list visable
mysqli_data_seek($result, 0);
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['userid'];
$sqlString = "SELECT name FROM users WHERE id='$id'";
$result = mysqli_query($dbLink, $sqlString) or die("Could not search for user.." . mysqli_error($dbLink));
$row = mysqli_fetch_assoc($result);
$name = $row['name'];
// echo users
echo "<h2 class=\"browsecategory\">Category: $cat</h2>
<p class=\"user\">Name: $name</p>\n";
}
}
if(isset($_POST['admins'])){
printusers(1, "Administrator");
}
I have also tried replacing the while loop with a foreach loop, like this:
foreach ($result as $row) {
same code as in while loop
}
This method echoed out several empty results. The HTML was there, but there was no information from the database. And the number of reults that were echoed was even higher than the number of results that the database should produce.
This is the HTML. A basic checkbox form:
<form action="results.php" method="POST">
<input type="checkbox" name="admins" id="admins">
<input type="checkbox" name="users" id="users">
<input type="checkbox" name="maillist" id="maillist">
<input type="submit" value="Browse">
</form>
I want to build a form to change the data in MySQL table. Firstly, I list all the data in the adminindex.php page. Then, I create a button to open the selected data in a form. I've done assigning the form fields to the main (pk) MySQL table. My problem started there when I need to fetch the foreign table data as the table contains many foreign data. As you guys know, a class may have many students, I have created the fields for class data, now the problem is in students data. Do I have to create many fields to fetch the data from MySQL foreign tables? If yes, could you guys guid me the code steps ? Thank you very much. Really appreciate your help :D
These are my steps:
Firstly I echo the rows, then I codes the form actions. Then, in adminpost.php, I create variables, link the fields and use UPDATE MYSQL to update the data in tables. I've succeeded in updating the primary table data but I'm stuck in foreign key data. Thanks :D
Have 2 pages. Display data in a form in first one and have update in the second. Here is a code for doing it one by one, you can build on it for multiple rows at a time if you want to.
edit.php
<?php
mysql_connect('ip', 'username', 'password') or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query = mysql_query("SELECT * FROM table1 where order by question_id limit 1") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$id = $row['id'];
$value1= $row['value1'];
$value2= $row['value2'];
}
?>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?php echo $id;?>">
Value1: <input type="text" name="value1" value="<?php echo $value1;?>">
<br>
Value2: <input type="text" name="value2" value="<?php echo $value2?>">
<input type="Submit" value="Change">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
update.php
<?php
mysql_connect('ip', 'username', 'password') or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$id = mysql_real_escape_string($_POST["ID"]);
$value1 = mysql_real_escape_string($_POST["value1"]);
$value2 = mysql_real_escape_string($_POST["value2"]);
$query="UPDATE table1 SET value1 = '.$value1.', value2 = '.$value2.' WHERE id='$id'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>($id) Record Updated<p>";
}else{
echo "<p>($id) Not Updated<p>";
}
?>
Next
Might help to put your actual code up, but as i understand you are just wanting to edit the data that is already in your table? If thats the case :
//Connect to SQL DB
$dbcnx = #mysql_connect("localhost", "root", "password");
//Select DB
mysql_select_db("database_name", $dbcnx);
//Query DB
$sql = update table_name set column_name = "$variable" where column = "your_criteria";
#mysql_query($sql)
That will connect you to your SQL DB and update the records for you, hope thats what you needed
Hello I am trying to understand why this isn't working on my page. I am using the php block below to use the variable I created at the beginning of my page $sel_subj (I used $_GET to get the id of what I clicked on on the previous page. I want the new page to reflect the data of the link I clicked on) I got the url to work to show the correct number from the database but I cannot get my page to display the name of what link was pressed; aka the data in the column labeled 'subject_name' from the 'subjects' table.
<?php
$query = "SELECT * FROM subjects WHERE id = \"$sel_subj\"";
$result_set = mysql_query($query, $connection);
if(!$result_set) {
die("Database query failed: " . mysql_error());
$subject = mysql_fetch_array($result_set);
return $subject;
?>
into this h2 tag right here.
<h2><?php echo $subject['subject_name']; ?>Hello</h2>
I can post the whole page if it will help. I appreciate everyone's input.
Thank you.
edit:new problems
Here is the bottom half of my code. I have a navigation div above this code which separates the links to the pages that relate to the database tables from the content that I'd like to pull from the db and display in the div for the page table.
However with the code I've provided nothing is showing up on the page when I open it in firefox. In my html when I "view source" while previewing on the testing server there is nothing underneath ...
<td id="page">
<?php
$query = "SELECT * FROM subjects WHERE id ='$sel_subj'";
$result_set = mysql_query($query, $connection);
if(!$result_set)
die("Database query failed: " . mysql_error());
$subject = mysql_fetch_assoc($result_set);
return $subject;
?>
<h2><?php echo $subject['subject_name']; ?>Hello</h2>
<br />
<?php echo $sel_page; ?><br />
<?php echo $sel_subj; ?><br />
<?php echo $subject; ?><br />
<?php echo $subject['id']; ?>
</td>
Change this:
$query = "SELECT * FROM subjects WHERE id = \"$sel_subj\"";
to this:
$query = "SELECT * FROM subjects WHERE id = '$sel_subj'";
and this:
$subject = mysql_fetch_array($result_set);
to this:
$subject = mysql_fetch_assoc($result_set);
PS: Try not to use the mysql class of functions anymore, they're not too good. Instead, use mysqli or PDO.
EDIT
If the column id is of numeric type, remove the apostrophes from the query. Like this:
$query = "SELECT * FROM subjects WHERE id = $sel_subj";
Try This
$query = "SELECT * FROM subjects WHERE id = '$sel_subj' ";
Try this
$query = "SELECT * FROM subjects WHERE id = {$sel_subj} ";
I have 2 tables in my database. categories and products. in categories there are 2 fields. catid and catname. and in products also there are 3 fields. id, catid and name.
in my submit form im fetching the catname in to a sector. what i wanna do is get value of the selector and save the catid in to products table catid field. instead of categories name. can anyone explain me how to do this. Thanks in advance.
Here is the code of submit form.
include("db.php");
$result = mysql_query("SELECT * FROM categories")
or die (mysql_error());
?>
<!--SubmitForm-->
<form method="post" action="add_products.php">
<select name="cat">
<?php
while($row = mysql_fetch_array($result))
{echo "<option value='".$row[catid]."'>".$row[catname]."</option>";}
?>
</select><br/>
<input type="text" name="name" value=""><br/>
<input type="submit" value="submit"/>
</form>
add_products.php Code
<?php
include("db.php");
$cat = $_POST['catid'];
$query = "SELECT * FROM categories WHERE catname='$cat'";
$result= mysql_query($query) or die ('Mysql Error');
while($row = mysql_fetch_array($result)){
$catn = $row['catid'];
}
$name = mysql_real_escape_string($_POST['name']);
$query="INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
?>
You already seem to have the right values, just need to put them in the correct spot, if you need the 'catid', you can just put it in the id tag of the select.
When you echo the you just need to do this,
echo "<option id='".$row[catid]."' value='".$row[cat]."'>".$row[catname]."</option>";
For more info refer to the w3school manual for , at this link.
Some unrelated, but very important things:
you should escape $cat before it goes into the query
you should always escape strings that go out to HTML with htmlspecialchars
you should always use $row['keyname'], not the deprecated $row[keyname]
Now for your question. The code seems correct on first glance, but I don't have PHP right now so I can't test it. Is there anything in particular that is not working as expected?
You already have it in??
$cat = $_POST['catid'];
If you only want to insert IF they $cat exists, then:
<?php
include("db.php");
$cat = $_POST['catid'];
$query = "SELECT * FROM categories WHERE catname='$cat'";
$result= mysql_query($query) or die ('Mysql Error');
if($result)
{
$name = mysql_real_escape_string($_POST['store']);
$query="INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
}
?>
You are already assigning the category ID to the category name in the select menu. The variable of the select menu is $_REQUEST['cat'], which holds the ID of the selected category after submitting the form. You can save this value directly to the product table.
However, the while loop in add_products.php is of no use, since you are always assigning the last ID in the table to the variable $catn. Replace this while loop with $catn = $_REQUEST['cat'] (while cat is the name of the select menu).
seem many mistakes here:
select name="cat"
and your try to receive $cat = $_POST['catid']; the correct is $cat = $_POST['cat'];
then you tries to select by catname
$query = "SELECT * FROM categories WHERE catname='$cat'";
when you need to compare ids catid='$cat'";
and what for to assign meny times if the result is single?:
if ( ($row = mysql_fetch_array($result)) ){
$catn = $row['catid'];
}
Your select field is names 'cat', so it should be $_POST['cat'] (or better, rename the select field to 'catid'). And it alreay contains the catid, so there's no need to get it from the DB again (unless you want to make sure it does in fact exist).
Finally, you should escape the $_POST['cat'] parameter as you do the name.
So this is sufficient:
$catid = mysql_real_escape_string($_POST['cat']);
$name = mysql_real_escape_string($_POST['store']);
$query="INSERT INTO products(catid, name) VALUES ('".$catid"','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
Please also look into PDO for the best way to handle DB queries like this.
try change this
"INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
to
"INSERT INTO products(catid, name)VALUES ('".$cat."','".$name."')";