Hi guys im working on an admin area for a CMS.
What I'm trying to figure out is how I can have a drop down menu to select a shop from the mysql database, and then use the details of that shop to submit it onto another page for invoicing. I'm not that great at PHP and I've had a look around but couldn't seem to find an answer. Here's the code. Thanks!
<?php
session_start();
if (!isset($_SESSION['username'])){
echo "You aren't logged in, please do so below<br>";
include('loginform.php');
exit();
}
?>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$con = mysqli_connect('localhost', 'root', '', 'aurora');
if (!isset($con)) {
echo "Connection to Aurora System failed.";
}
$username = $_SESSION['username'];
echo "$username";
$query = "SELECT area FROM users WHERE username = '$username'";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($result)){
$area = $row['area'];
}
$query2 = "SELECT * FROM shops WHERE county = '$area'";
$area_result = mysqli_query($con, $query2);
?>
<form action="time.php" method="POST">
<?php
echo '<br><select name="username">';
while($row2 = mysqli_fetch_assoc($area_result)){
echo '<option value="'. $row2['shop_id'].'">' . $row2['shopname'] . ' - ' .$row2['contactname']. ", " .$row2['streetaddress']. '</option>';
}
$shopid = $row2['shop_id'];
echo $shopid;
?>
</select><br><input type="submit" value="Register" name="register_button"> <br></form>
</body>
</html>
Remove:
echo $shopid;
It might not fix your problem but you definitely don't want extra strings in the select element
Not sure what you're asking, but I think this chunk of my own code might be it:
<select class="form-control" name="categoria">
<option value="">Selecciona una categorÃa</option>
<?php
$q = 'SELECT * FROM categoria';
$resultado = mysqli_query($db,$q);
while($row = mysqli_fetch_assoc($resultado)){
$selected = "";
if(!empty($categoria) && $categoria == $row["categoria"]){
$selected = 'selected="selected"';
}
echo '<option value="'.$row["categoria"].'" '.$selected.'>'.$row["categoria"].'</option>';
}
Related
This question already has answers here:
Update a MySQL database field data with HTML form and PHP
(2 answers)
Closed 5 years ago.
So I'm currently playing around with PHP and making a "blog" system. I want to user to be able to edit the topic name of their own posts. Currently when you edit a topic name, all of the other topic names changes no matter which user made the post.
Only edit the current topic name.
Only the editor who made the post can edit that post.
topic.php
<?php
session_start();
require('connect.php');
if (#$_SESSION["username"]) {
?>
<!DOCTYPE html>
<html>
<head>
<title>Home page</title>
</head>
<body>
<?php include('header.php'); ?>
<center>
<?php
if (#$_GET['id']) {
$check = mysql_query("SELECT * FROM topics WHERE topic_id='".$_GET['id']."'");
if (mysql_num_rows($check) > 0) {
while ($row = mysql_fetch_assoc($check)) {
$check_u = mysql_query("SELECT * FROM users WHERE username='".$row['topic_creator']."'");
while ($row_u = mysql_fetch_assoc($check_u)) {
$user_id = $row_u['id'];
}
echo "<h1>".$row['topic_name']."</h1>";
echo "<h5>By <a href='profile.php?id=$user_id'>".$row['topic_creator']."</a><br />Date: ".$row['date']."</h5>";
echo "<br />".$row['topic_content'];
echo "<br /><br /><img src='img/".$row['image']."' width='300' />";
echo "<br /><br /><a href='edit.php?edit=".$row['topic_id']."'>Edit</a>";
}
}else {
echo "Topic not found.";
}
}
?>
</center>
</body>
</html>
<?php
}else {
echo "You must be logged in.";
}
?>
edit.php
<?php
session_start();
require('connect.php');
if (#$_SESSION["username"]) {
?>
<!DOCTYPE html>
<html>
<head>
<title>Home page</title>
</head>
<body>
<?php include('header.php'); ?>
<center>
<?php
if( isset($_GET['edit']) )
{
$id = $_GET['edit'];
$res= mysql_query("SELECT * FROM topics");
$row= mysql_fetch_assoc($res);
}
if( isset($_POST['newTn']) )
{
$newTn = $_POST['newTn'];
// $id = $_POST['id'];
$sql = "UPDATE topics SET topic_name='$newTn'";
$res = mysql_query($sql)
or die("Could not update".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=index.php'>";
}
?>
<form action="edit.php" method="POST">
Name: <input type="text" name="newTn" value=<?php echo $row['topic_name']; ?>><br />
<input type="hidden" name="id" value="">
<input type="submit" value=" Update "/>
</form>
</center>
</body>
</html>
<?php
if (#$_GET['action'] == "logout") {
session_destroy();
header("Location: login.php");
}
}else {
echo "You must be logged in.";
}
?>
Thanks beforehand!
//E
In edit.php
You need to specify the post id to be edited in the query.
if( isset($_POST['newTn']) )
{
$newTn = $_POST['newTn'];
$id = $_POST['id'];
//notice here the $id is added as where clause to filter the edit on one row only
$sql = "UPDATE topics SET topic_name='$newTn' WHERE post_id = '$id'";
$res = mysql_query($sql)
or die("Could not update".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=index.php'>";
}
$sql = "UPDATE topics SET topic_name='$newTn' where topic_id = '".$_GET['edit]."'";
You have passed the topic id from Grid and you need to attach that in query
You need to specifies the id of the topic in the query UPDATE :
$sql = "UPDATE topics SET topic_name='$newTn' where id=$session[yourtopicID]" ;
In edit.php change UPDATE topics SET topic_name='$newTn' query to below
UPDATE topics SET topic_name = '$newTn' where `yourTopicId` = '$_GET[edit]'
I am working on a school assignment and I have run into some issues. I have PHP code for a form that, when selected, sends the selected result to a MySQL database and then loops through and displays the results. The only problem is that, instead of showing the selected <option>, it shows all four of the options.
Here is my code:
<?php
include_once (connection.php);
if (($_SERVER["REQUEST_METHOD"] == "POST") && (isset($_POST['card_catalog_form']))) {
$card_name = mysqli_real_escape_string($conn, $_POST['card_name']);
$card_label = mysqli_real_escape_string($conn, $_POST['card_label']);
$insert_card_genre_query = sprintf("INSERT into card_catalog (card_name, card_label) VALUES ('%s', '%s')",
$card_name,
$card_label);
$insert_card_genre = mysqli_query($conn, $insert_card_genre_query) or die (mysqli_error($conn));
$last_record = mysqli_insert_id($conn);
}
$card_genre_query = "SELECT card_genre.genre_id, card_label from `card_genre` order by card_label asc";
$card_genre = mysqli_query($conn, $card_genre_query) or die(mysqli_error($conn));
$get_card_genre_query = "SELECT card_catalog.id, card_catalog.card_name, card_catalog.card_label, card_genre.genre_id from card_catalog right join card_genre on card_catalog.card_label = card_genre.card_label";
$get_card_genre = mysqli_query($conn, $get_card_genre_query) or die(mysqli_error($conn));
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>The Marketplace By The Mana Club</title>
<link rel="stylesheet" type="text/css" href="stylesheets/tmp.css">
</head>
<body>
<?php include(templatestuff/top_of_tmp.php); ?>
<main>
<h1>Products:</h1>
<section>
<ul id="products_list">
<li><b>Product 1: "Jack-In-The-Mox"</b></li>
<li><b>Product Description: "Roll a six-sided die for Jack-in-the-Mox. On a 1, sacrifice Jack-in-the-Mox and lose 5 life. Otherwise, Jack-in-the-Mox has one of the following effects. Treat this ability as a mana source..."</b></li>
<img src="productimages/jackinthemox.jpeg" alt="Jack In The Mox"/>
</ul>
</section>
<div>
<h2>What Card Are You Looking For?</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
<fieldset>
<p><b>What's The Card Name? <input type="text" name="card_name"></b></p>
<p>
<p><b>Card Type:</b></p>
<select name="card_genre">
<?php while ($row_card_genre = mysqli_fetch_assoc($card_genre)) { ?>
<option value="<?php echo $row_card_genre['genre_id'];?>"><?php echo $row_card_genre['card_label'];?></option>
<?php } ?>
</select>
</p>
<p><input type="submit"></p>
<input type="hidden" name="card_catalog_form">
</fieldset>
</form>
<?php
if ($last_record) {
echo "<p><b>You just created form query #" . $last_record ."</b><p>";
}
?>
<p>You are submitting your form at
<?php
date_default_timezone_set('America/New_York');
echo date('g:i a \o\n l, F j, Y');
?>
</p>
</div>
<?php
$query = "SELECT card_catalog.card_name, card_catalog.card_label, card_genre.genre_id FROM card_catalog, card_genre";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result)){
echo $row['card_name']. " - ". $row['genre_id'];
echo "<br />";
}
?>
</main>
<?php include('templatestuff/bottom_of_tmp.php'); ?>
</body>
</html>`
(If you want to see the website that contains the problem, you can go here)
Any help, or constructive criticism, would be greatly appreciated.
Thanks
This might point you in the right direction:
if (isset($_POST['card_genre'])) {
$query = "SELECT card_catalog.card_name, card_catalog.card_label, card_genre.genre_id FROM card_catalog, card_genre WHERE card_genre.genre_id = ?";
$stmt = mysqli_prepare($conn, $query);
$stmt->bind_param('s', $_POST['card_genre']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['card_name']." - ".$row['genre_id'];
echo "<br />";
}
} else {
$query = "SELECT card_catalog.card_name, card_catalog.card_label, card_genre.genre_id FROM card_catalog, card_genre";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_array($result)) {
echo $row['card_name']." - ".$row['genre_id'];
echo "<br />";
}
}
I am in the process of creating a filter page that should return a table of results dependent upon the selection chose from a drop down list.
I have generated the code for this and no errors are found. However, no results show up despite them being present in the database.
Am I missing something?
Please let me know if any further information is required.
Any help would be greatly appreciated!
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');
$search_output= "";
$link= mysqli_connect("localhost","root","");
mysqli_select_db($link,"assessment_centre_app");
if(isset($_POST['submit'])) {
$Name_FK = $_POST['Name_FK'];
$sqlCommand = mysqli_query($link, "SELECT *
FROM scores
WHERE 'Name_FK' = {'$Name_FK'}");
$query = mysql_query($sqlCommand) or die (mysql_error());
$count = mysqli_num_rows($query);
if($count > 1) {
$search_output .="$count results for $searchquery";
while($row = mysql_fetch_array($query)) {
$Candidate_Name_FK = $row["Candidate_Name_FK"];
$search_output .="Item ID: $Candidate_Name_FK <br />";
}
} else {
$search_output= "0 results found";
}
}
?>
<html>
<head>
</head>
<body>
<form action="http://localhost/scoresheet/scoresheetfilter.php" method="POST">
<label> Assessment Day Name </label>
<select name = "Name_FK">
<?php
$res=mysqli_query($link,"SELECT * FROM scores");
while($row=mysqli_fetch_array($res))
{
?>
<option>
<?php echo $row["Name_FK"]; ?>
</option>
<?php } ?>
</select>
<br>
<input name ="myBtn" id="submit" type="submit" >
<br>
</form>
<div>
<?php echo $search_output;
?>
</div>
</body>
</html>
Try this out if it still does not display anything the check the variable used to call this other one's
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');
$search_output= "";
$link= new mysqli("localhost", "user_name", "password", "database");
if(isset($_POST['submit'])) {
$Name_FK = $_POST['Name_FK'];
$sqlCommand = "SELECT * FROM scores WHERE Name_FK='$Name_FK'";
$query = mysqli_query($linnk, $sqlCommand) or die (mysqli_error());
$count = mysqli_num_rows($query);
if($count > 1) {
$search_output .="$count results for $searchquery";
while($row = mysqli_fetch_array($query)) {
$Candidate_Name_FK = $row["Candidate_Name_FK"];
$search_output .="Item ID: $Candidate_Name_FK <br />";
echo $search_output; //echo to check result
}
} else {
$search_output= "0 results found";
echo $search_output; //echo to check result
}
}
?>
Now edited
variable
$searchquery
not created
I am trying to populate a mysql associative (many to many) table via a form submit. Basically, trying to use this page to associate a "Red Flag" to one-to-many "Products".
Screenshot of input form
FORM
<?php
require 'connect-db.php';
$sql = "SELECT ID, prod_name FROM catalog";
$result = mysqli_query($mysqli, $sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p><strong>Add Red Flag:</strong></p>
<form action="addRedFlag.php" method="post" id="rfForm">
<p>Description:
<br/><textarea rows="4" cols="50" name="rfDescription" form="rfForm"></textarea>
<p>Severity: <br/>
<input type="radio" name="severity" value="minor"/>Minor<br/>
<input type="radio" name="severity" value="moderate"/>Moderate<br/>
<input type="radio" name="severity" value="major"/>Major<p/>
<select name="prod_id">
<option value="">Choose a product</option>
<?php while($row = mysqli_fetch_assoc($result)){ ?>
<?php $id = $row['ID']; ?>
<?php $title = $row['prod_name']; ?>
<option value="<?php echo $id; ?>"><?php echo $title; ?></option>
<?php } ?>
</select>
<p/><input type="submit" value="Submit" name="submit" /></form><br>
Reset Form <br>
View Red Flag List<br>
Home
</body>
</html>
PHP HANDLER
<?php
// connect to the database
include("connect-db.php");
$value1 = $_POST['rfDescription'];
$value2 = $_POST['severity'];
$value3 = $_POST['prod_id'];
$sql = "INSERT INTO redFlag (description, severity) VALUES ('$value1', '$value2')";
$sql2 = "SELECT ID FROM redFlag WHERE (description = '$value1')";
$sql3 = "INSERT INTO prod_RF (cat_id, rf_id) VALUES ('$value3', '$value4')";
$result1 = mysqli_query($mysqli, $sql);
$result2 = mysqli_query($mysqli, $sql2);
if ($result1)
{
if ($result2)
{
$row = mysqli_fetch_assoc($result2);
$value4 = $row['ID'];
// echo $value4;
$result3 = mysqli_query($mysqli, $sql3);
if ($result3)
{
echo "success";
}
else {echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);}
}
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
?>
When executed, the code completes successfully BUT the value of rf_id in prod_RF table is always zero. This is strange because when I uncomment the
echo $value4;
line, the expected value is printed to the screen. For some reason, when I attempt to use that same value ($value4) as input to a SQL query ($sql3), something fails.
Thanks for any suggestions as I'm pretty new to all this.
A better way to do this is to use the MySQL function to get the last insert id so you can skip the second query.
$sql = "INSERT INTO redFlag (description, severity) VALUES ('$value1', '$value2')";
$sql3 = "INSERT INTO prod_RF (cat_id, rf_id) VALUES ('$value3', LAST_INSERT_ID())";
$result1 = mysqli_query($mysqli, $sql);
$result2 = mysqli_query($mysqli, $sql3);
// the $result2 query will insert the rf_id
// so you can test this result to see if it's all successful
That should remove a nice chunk of PHP from your code.
It looks like $value4 is not defined until after the $sql3 string has been crafted. Try defining $sql3 after you have defined $value4.
Thanks to stackoverflow.com's frienly experts I've managed to create my first php + mysql application.
The code searches a mysql database for last names and cities. The choices are made through two drop lists like these:
Choose city:
All cities
Liverpool
Manchester
Choose last name:
All last names
Lennon
Gallagher
The code would return eg. all the Lennons living in Liverpool.
However, I haven't been able to make the options "All cities" and "All last names" to work so that the code would return eg. all the Lennons living in any city or all the people living in Liverpool. So, how can that be done?
The code so far:
index.php
<?php
$conn = mysql_connect('localhost', 'user', 'password') or die("Connection failed");
mysql_select_db("database", $conn) or die("Switch database failed");
//this gets the cities from the database to the drop list
$query = "SELECT DISTINCT city FROM user".mysql_real_escape_string($city);
$result = mysql_query($query, $conn);
$options="";
while ($row=mysql_fetch_array($result)) {
$city=$row["city"];
$options.="<OPTION VALUE=\"$city\">".$city;
}
//this gets the last names from the database to the drop list
$query2 = "SELECT DISTINCT lastname FROM user".mysql_real_escape_string($lastname);
$result2 = mysql_query($query2, $conn);
$options2="";
while ($row2=mysql_fetch_array($result2)) {
$lastname=$row2["lastname"];
$options2.="<OPTION VALUE=\"$lastname\">".$lastname;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>test</title>
</head>
<body>
<form action="get.php" method="post">
<p>
<select name="city">
<option value=0>Choose
<option value=1>All cities
<?=$options?>
</select>
</p>
<p>
<select name="lastname">
<option value=0>Choose
<option value=1>All last names
<?=$options2?>
</select>
</p>
<p>
<input value="Search" type="submit">
</p>
</form>
<br>
</body>
</html>
get.php
<?php
$conn = mysql_connect('localhost', 'user', 'password') or die("Connection failed");
mysql_select_db("database", $conn) or die("Switch database failed");
$query = "SELECT * FROM user WHERE city = '".mysql_real_escape_string($_POST['city'])."' AND lastname = '".mysql_real_escape_string($_POST['lastname'])."'";
$result = mysql_query($query, $conn);
echo $rowcount;
$zerorows=true;
while ($row = mysql_fetch_assoc($result))
{
$zerorows=false;
echo '<b>City: </b>'.htmlspecialchars($row[city]).'<br />';
echo '<b>Last name: </b>'.htmlspecialchars($row[lastname]).'<br />';
echo '<b>Information: </b>'.htmlspecialchars($row[information]).'<br />'.'<br />';
}
if($zerorows) echo "No results";
mysql_close($conn);
?>
Just have a special value for all (such as ALL) and put in:
if ($_POST['city'] == 'ALL')
{
$sql_city = '1';
}
else
{
$sql_city = "city = '".mysql_real_escape_string($_POST['city'])."'";
}
if ($_POST['lastname'] == 'ALL')
{
$sql_lastname = '1';
}
else
{
$sql_lastname = "lastname = '".mysql_real_escape_string($_POST['lastname'])."'";
}
$query = "SELECT * FROM user WHERE ".$sql_city." AND '".$sql_lastname."";
Then build the SQL statement based upon the the if's. The reason you use 1 is that it always evaluates to true.