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 />";
}
}
Related
I am currently working on a school project and I need a little help. I am writing PHP/SQL code for a page where, when the user submits a form, a query runs that loops through and displays the user text input and also the value associated with the <select> dropdown.
(For a visual idea of what I mean, visit http://themanaclub.com/themarketplace2/themarketplace2.php)
Here is my code:
<?php
include_once ('connection2.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_genre']);
$insert_card_genre_query = sprintf("INSERT into card_catalog (card_name, label_id) VALUES ('%s', %u)",
$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 genre_id desc";
$card_genre = mysqli_query($conn, $card_genre_query) or die(mysqli_error($conn));
$get_card_genre_query = "SELECT card_catalog.id, card_name, label_id, card_label from card_catalog left join card_genre on label_id = genre_id";
$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="stylesheets2/tmp2.css">
</head>
<body>
<?php include('templatestuff2/top_of_tmp2.php'); ?>
<main>
<h1>Card Input Form:</h1>
<form id="card_name_entry" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
<h4>What Card Are You Looking For?</h4>
<textarea name="card_label" rows="5" cols="30" placeholder="Write the name of the card here"></textarea>
<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'];?><?php echo $row_card_genre['card_name'];?></option>
<?php } ?>
</select>
</p>
<?php $query = "SELECT label_id from `card_catalog` right join `card_genre` on genre_id"; ?>
<p id="textareasubmit"><input type="submit"></p>
<input type="hidden" name="card_catalog_form">
</form>
<section id="all_questions">
<ul>
<?php while ($row_card_genre = mysqli_fetch_assoc($get_card_genre)) { ?>
<li><?php echo $row_card_genre['card_label'];?></li>
<?php }
$row_card_genre = mysqli_data_seek($get_card_genre, 0);
?>
</ul>
</section>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
<p id="deletethissubmit"><input type="submit" value="Delete This"></p>
<input type="hidden" name="card_catalog_delete">
<input type="hidden" name="genre_id" value="<?php echo $row_card_catalog['label_id'];?>"
</form>
<p>You're asking this at
<?php
date_default_timezone_set('America/New_York');
echo date('g:i a T \o\n l, F j, Y');
?>
</p>
<p id="backtothemarketplace">Back To The Marketplace</p>
<?php
/*if (isset($_POST['card_genre'])) {
$query = "SELECT card_catalog.card_name, card_catalog.label_id, card_genre.genre_id, card_genre.card_label 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['label_id'];
echo "<br />";
}
}*/
?>
</main>
<?php include('templatestuff2/bottom_of_tmp2.php'); ?>
</body>
</html>
If anybody has any help or constructive criticism, it would be greatly appreciated (I'm a PHP/SQL newbie so I'll take all the help that I can get).
Thanks
Messed around with the code and I fixed it. The id is now being displayed and it links to the correct page.
All that was wrong with my code was that I mixed up some of the variables and ids.
Thank you all for your help.
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>';
}
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 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.
I am trying to update 3 tables and insert on 2. The thing is I get errors and I get some tables to update and insert, I am thinking there is a better way to put this. Please give me some wonderful input. Sorry that this is horrible coding. :(
<?php
require 'includes/db_connect.php';
if ( !empty($_POST)) {
// keep track validation errors
$vehiclenumError = null;
$chauffeuridError = null;
// keep track post values
$alias = $_POST['alias'];
$vehiclenum = $_POST['vehiclenum'];
$chauffeurid = $_POST['chauffeurid'];
// validate input
$valid = true;
if (empty($vehiclenum)) {
$vehiclenumError = 'Please select a Vehicle #';
$valid = false;
}
if (empty($chauffeurid)) {
$chauffeuridError = 'Please select a Chauffeur #';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO unit_logs (alias,vehiclenum,chauffeurid,status) values (?, ?, ?, 1)";
$sql1 = "INSERT INTO active_units (alias,vehiclenum,chauffeurid,status) values (?, ?, ?, 1)";
$sql2 = "UPDATE ipads SET status='1' WHERE alias=$alias";
$sql3 = "UPDATE vehicles SET active='1' WHERE vehiclenum=$vehiclenum";
$sql4 = "UPDATE chauffeurs SET active='1' WHERE chauffeurid=$chauffeurid";
$q = $pdo->prepare($sql);
$l = $pdo->prepare($sql1);
$x = $pdo->prepare($sql2);
$z = $pdo->prepare($sql3);
$h = $pdo->prepare($sql4);
$q->execute(array($alias,$vehiclenum,$chauffeurid));
$l->execute(array($alias,$vehiclenum,$chauffeurid));
$x->execute(array($alias));
$z->execute(array($vehiclenum));
$h->execute(array($chaffeurid));
Database::disconnect();
header("Location: testing.php");
}
}
?>
<code>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Tablet Check Out</h3>
</div>
<?php
mysql_connect('localhost', 'allen', 'w0wr0cks');
mysql_select_db('wcldb');
$sql = "SELECT alias FROM ipads WHERE status = 0 ORDER BY alias ASC";
$result = mysql_query($sql);
?>
<form class="form-horizontal" action="checkout.php" method="post">
<div class="control-group">
<label class="control-label">Tablet Alias</label>
<div class="controls">
<select name="alias">
<?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['alias'] ."'>" . $row['alias'] ."</option>";
} ?>
</select>
</div>
</div>
<?php
mysql_connect('localhost', 'allen', 'w0wr0cks');
mysql_select_db('wcldb');
$sql = "SELECT vehiclenum FROM vehicles WHERE ownertype = 'JKS' AND active = '0' ORDER BY vehiclenum ASC";
$result = mysql_query($sql);
?>
<div class="control-group <?php echo !empty($vehiclenumError)?'error':'';?>">
<label class="control-label">Vehicle #</label>
<div class="controls">
<select name="vehiclenum">
<?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['vehiclenum'] ."'>" . $row['vehiclenum'] ."</option>";
}
echo '</select>';
?>
</div>
</div>
<?php
mysql_connect('localhost', 'allen', 'w0wr0cks');
mysql_select_db('wcldb');
$sql = "SELECT chauffeurid FROM chauffeurs WHERE ownertype = 'JKS' AND active='0' ORDER BY chauffeurid ASC";
$result = mysql_query($sql);
?>
<div class="control-group <?php echo !empty($chauffeuridError)?'error':'';?>">
<label class="control-label">Driver #</label>
<div class="controls">
<?php
echo "<select name='chauffeurid'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['chauffeurid'] ."'>" . $row['chauffeurid'] ."</option>";
}
echo '</select>';
?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="testing.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>