PHP - Insert Into Associative Table - php

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.

Related

How do I add values to a dependent dropdown list in PHP?

I have two columns in my database: faculty and department. I managed to bind the data to a drop-down containing my faculties. But for a department which has a foreign key to faculty, how do I add a new one and display it in a drop-down as well?
Basically, I need that when I select a faculty from the first drop-down, departments for that specific faculty will be shown in the second drop-down, and I can add another department to the selected faculty if I want to.How can I achieve this?
<?php
require('config.php');
include('auth.php');
$query = "SELECT name, faculty_id FROM faculty ORDER BY name ASC";
$result = mysqli_query($con, $query);
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<< Go back
<br><br>
<form action="/admin/departments/" method="post">
<select name="faculties">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['faculty_id'] . "'>" . $row['name'] . "</option>";
}
?>
</select>
</form>
<?php
if (isset($_POST['save_department'])) {
$sql = "INSERT INTO department (name) VALUES ('" . $_POST["department_name"] . "')";
$result = mysqli_query($con, $sql);
}
$query = "SELECT name, faculty_id, department_ID FROM department ORDER BY name ASC";
$result = mysqli_query($con, $query);
?>
<br><br>
<form action="/admin/departments/" method="post">
<select name="departments">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['department_ID'] . "'>" . $row['name'] . "</option>";
}
?>
</select>
</form>
<br>
<form method="POST" action="">
<input name="department_name" type="text" required="required"><br>
<br>
<button type="submit" name="save_department">Add Department</button>
</form>
</body>
</html>
Please else with if condition or make query dynamically as:
$query = '';
if (isset($_POST['save_department'])) {
$query = "INSERT INTO department (name) VALUES ('" .
$_POST["department_name"] . "')";
}else{
$query = "SELECT name, faculty_id, department_ID FROM department ORDER BY name ASC";
}
$result = mysqli_query($con, $query);

MySQL/PHP <select> not displaying submitted value

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 />";
}
}

Solving the return value of an SQL Query in an Associative Array

Once again I am at the mercy of your knowledge and hope you can help.
Actual question is the bold italics, however you won't be able to help without reading the information that I've given.
Background to Question - I'm creating a photography website (for my mum) using HTML, CSS, MySQL and PHP. I'm in the process of working on the database, specifically on allowing my mum to insert images into the database using this form (http://i.imgur.com/h4nXFFA.png). She has no idea how to code, therefore I need to make it easy for her.
Database Background (what you need to know) - I've got an image_tbl and album_tbl. The album_tbl is shown here - http://i.imgur.com/4GXh9MP.png - with each album having an ID and Name (forget the 'hidden'). The image_tbl is shown here - http://i.imgur.com/RgC35Nd.png - with the important part (for this question) being the albumName.
Aim - I've managed to populate the 'Insert a New Image' form with the albums from album_tbl (picture shows 'Exploration'). I want her to be able to click the AlbumName (so she knows what album to add to), yet I want the image she inserts to receive the albumID in the database. Here's a Pastebin of my code thus far.
http://pastebin.com/6v8kvbGH = The HTML Form, for helping me be aware of the 1st Form in the code...
http://pastebin.com/4X6abTey = PHP/MySQL Code. Here we have me calling the inputs in the form and using them in 2 SQL Queries. The first Query is aiming to get the albumID of the albumName that was entered, and this is where it goes wrong. The commented out statements (using //) are me error-checking, and albumName is passed on from the form. However, the number of rows returned from the 1st SQL Statement is 0, when it should be 1. This is where I need help as clearly something's wrong with my assoc array ...
2nd Aim - Once the 1st SQL Query is working, the 2nd SQL Query is hopefully going to input the required variables into image_tbl including the albumID I hopefully just got from the 1st SQL Query.
I hope this is all that's required, as far as I'm aware the people who understand this should be able to help with what I've given. Thanks very much in advance!
Jake
Someone asked me to paste the code - HTML Form:
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['albumName'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
Inserting the image using PHP/MySQL:
<?php
$username="root";
$password="";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumName = $_POST['albumName'];
// echo "album name is" . $albumName;
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
$albumID = $conn->query($sql);
// echo "Number of rows is " . $albumID->num_rows;
if ($albumID->num_rows > 0) {
// output data of each row
while($row = $albumID->fetch_assoc()) {
echo "Album ID: " . $row["albumID"]. "<br>";
}
} else {
echo "0 results";
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
This line:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
should be:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = '$albumName'";
since the album name is a string.
You should check for errors when you perform a query:
$albumID = $conn->query($sql) or die($conn->error);
You can't use $albumID in the INSERT query. Despite the name of the variable, it doesn't contain an album ID, it contains a mysqli_result object that represents the entire resultset of the query -- you can only use it with methods like num_rows and fetch_assoc() to extract information from the resultset.
What you can do is use a SELECT statement as the source of data in an UPDATE:
$stmt = $conn->prepare("INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT ?, ?, ?, ?, ?, ?, albumID
FROM album_tbl
WHERE albumName = ?";
$stmt->bind_param("sssssss", $name, $dateTime, $caption, $comment, $slideshow, $hidden, $albumName);
$stmt->execute();
Note that when you use a prepared query, you don't need to fix the quotes in $comment (which you should have done using $conn->real_escape_string($comment), not str_replace()).
Just to help you understand, this can also be done without a prepared query.
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT '$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', albumID
FROM album_tbl
WHERE albumName = '$albumName'";
First of all create a single database connection let say
db_connection.php
<?php
$username="root";
$password="1k9i2n8gjd";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
Then in your form or any php file that needs database connection you can just include the db_connection.php so that you have one database connection.
Note: I have change the value of option to albumId so that you dont need to query or select based on albumName because you already have the albumID passed in imagesInsert.php via $_POST
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
?>
<html>
<head>
<title>Admin Page | Alison Ryde's Photography</title>
<link rel="stylesheet" type="text/css" href="../../css/style.css">
</head>
<body>
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = $conn->query($sql);// mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['albumID'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
</html>
Then in your php code that inserts the data should be like this.
imagesInsert.php
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
Another piece of advice is to use prepared statementif your query is build by users input to avoid sql injection
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssss", $name, $dateTime, $caption,$new_comment,$slideshow,$hidden,$albumID);
$stmt->execute();
hope that helps :) good luck

updating database update

I am having trouble getting the database to update. Is there something wrong with my sql update statement? I checked the sql statement and it says that there were no records in the database. I am not sure what to do.
<!-- template for mySql database access. -->
<!DOCTYPE html>
<html>
<head>
<title>CRUD</title>
<link href="/sandvig/mis314/assignments/style.css" rel="stylesheet" type="text/css">
</head>
<div class="pageContainer centerText">
<h3>CRUD (Create, Read, Update, & Delete) Database</h3>
<?php
//include database connection
include("DatabaseConnection2.php");
//connect to database
$link = fConnectToDatabase();
//Retrieve parameters from querystring and sanitize
$nameF = fCleanString($link, $_GET['nameF'], 15);
$nameL = fCleanString($link, $_GET['nameL'], 15);
$deleteID = fCleanNumber($_GET['deleteID']);
$updateID = fCleanNumber($_GET['updateID']);
$updateID2 = fCleanNumber($_GET['updateID2']);
//Populate Textbox
if (!empty($updateID)) {
$sql = "SELECT NameL, NameF
FROM customertbl
WHERE custID = '$updateID'";
mysqli_query($link, $sql) or die('Delete error: ' . mysqli_error($link));
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
$row = mysqli_fetch_array($result);
$strFName2 = $row[NameF];
$strLName2= $row[NameL];
}
?>
<hr>
<form class="formLayout">
<div class="formGroup">
<label>First name:</label>
<input name="nameF" type="text" autofocus value="<? echo $strFName2; ?>">
</div>
<div class="formGroup">
<label>Last name:</label>
<input name="nameL" type="text" value="<? echo $strLName2; ?>">
</div>
<div class="formGroup">
<label> </label>
<button>Submit</button>
<input type="hidden" name="updateID2" value="<? echo $updateID; ?>">
</div>
</form>
<?php
//Update
if (!empty($updateID2))
{
$sql = "UPDATE customertbl
SET NameL = '$strFName2', NameF ='$strLName2'
WHERE custID = '$updateID2' ";
mysqli_query($link, $sql) or die('Insert error: ' . mysqli_error($link));
}
//Insert
if (!empty($nameF) && !empty($nameL)) {
$sql = "Insert into customertbl (NameL, NameF)
VALUES ('$nameL', '$nameF')";
mysqli_query($link, $sql) or die('Insert error: ' . mysqli_error($link));
}
//Delete
if (!empty($deleteID)) {
$sql = "Delete from customertbl WHERE CustID= '$deleteID' ";
mysqli_query($link, $sql) or die('Delete error: ' . mysqli_error($link));
}
//List records
$sql = 'SELECT custID, NameF, NameL
FROM customertbl order by custID';
//$result is an array containing query results
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
echo "<p>" . mysqli_num_rows($result) . " records in the database</p>";
?>
<table class="simpleTable">
<tr>
<th>Cust. ID</th>
<th>F. Name</th>
<th>L. Name</th>
<th>Delete</th>
<th>Update</th>
</tr>
<?php
// iterate through the retrieved records
while ($row = mysqli_fetch_array($result)) {
//Field names are case sensitive and must match
//the case used in sql statement
$custID = $row['custID'];
echo "<tr>
<td>$custID</td>
<td>$row[NameF]</td>
<td>$row[NameL]</td>
<td><a href='?deleteID=$custID'>Delete</a></td>
<td><a href='?updateID=$custID'>Update</a></td>
</tr>";
}
?>
</table>
</div>
</body>
</html>
The offending code block
//Update
if (!empty($updateID2))
{
$sql = "UPDATE customertbl
SET NameL = '$strFName2', NameF ='$strLName2'
WHERE custID = '$updateID2' ";
mysqli_query($link, $sql) or die('Insert error: ' . mysqli_error($link));
}
makes references to variables $strFName2 and $strLName2 which are variables that are only populated conditionally.
//Populate Textbox
if (!empty($updateID)) {
$sql = "SELECT NameL, NameF
FROM customertbl
WHERE custID = '$updateID'";
mysqli_query($link, $sql) or die('Delete error: ' . mysqli_error($link));
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
$row = mysqli_fetch_array($result);
$strFName2 = $row[NameF];
$strLName2= $row[NameL];
}
Since the variables $strFName2 and $strLName2 are undefined during the UPDATE SQL query, you're not seeing the desired results.
The query should reference $nameF and $nameL since those variables are always defined (not contained within a conditional) and the form inputs use nameF and nameL in their name attributes.
$sql = "UPDATE customertbl
SET NameL = '$nameF', NameF ='$nameL'
WHERE custID = '$updateID2';";
You also need to fix your DELETE query to reference the column custID and not CustID as it appears your schema uses the former.
$sql = "Delete from customertbl WHERE custID= '$deleteID' ";

PHP how to insert select box value into database

i have a question
i already make a form to view two select box value with database and one text filed value
i want to know how to insert those value back into database with different table
my script on view select box value is something like this
<?php
$query = "SELECT gejala FROM gejala where idatribut =110000";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
?>
<select name="gejala1">
<?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['gejala']."'>".$row['gejala']."</option>";
}
?>
</select>
<p>Subatribut2
<?php
$query = "SELECT gejala FROM gejala where idatribut =110000";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
?>
<select name="gejala2">
<?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['gejala']."'>".$row['gejala']."</option>";
}
?>
</select>
<p>
<label>value
<input type="text" name="textfield">
</label>
<p>
<input name="submit" type="button" value="submit">
<p>
how to know how to insert this value into another table(pucuk) with same field
thankyou
i already try insert script
<?php
if(isset($_POST['gejala1'])) {
$gejala1 = $_POST['gejala1'];
$sql = "INSERT INTO pucuk (gejala1) VALUES ({$gejala2})";
$dbLink = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('cbrteh', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
if(isset($_POST['gejala2'])) {
$gejala2 = $_POST['gejala2'];
$sql = "INSERT INTO pucuk (gejala2) VALUES ({$gejala2})";
$dbLink = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('cbrteh', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
}
?>
</form>
but when i hit submit button it still has no effect
In while loop itself u can write insert query and send the option box value into the field u want,try it !
after a submit, your select option value will be in the $_POST[] variable under the name of your select. Namely, here "gejala2"
put your code in a form with method=POST and after submitting your form you will get all your new values in _POST array
for example
if(isset($_POST['submit']))
{
$var1=$_POST['select1'];
$var2=$_POST['select2'];
$var3=$_POST['select3'];
//then write update/insert query as your requirement
}
Try this
<?php
if(isset($_POST['gejala1'])) {
$gejala1 = $_POST['gejala1'];
$sql = "INSERT INTO pucuk (gejala1) VALUES ({$gejala2})";
$dbLink = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('cbrteh', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
if(isset($_POST['gejala2'])) {
$gejala2 = $_POST['gejala2'];
$sql = "INSERT INTO pucuk (gejala2) VALUES ({$gejala2})";
$dbLink = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('cbrteh', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
?>
<form action="" method="POST"><!-- add this -->
<?php
$query = "SELECT gejala FROM gejala where idatribut =110000";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
?>
<select name="gejala1">
<?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['gejala']."'>".$row['gejala']."</option>";
}
?>
</select>
<p>Subatribut2
<?php
$query = "SELECT gejala FROM gejala where idatribut =110000";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
?>
<select name="gejala2">
<?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['gejala']."'>".$row['gejala']."</option>";
}
?>
</select>
<p>
<label>value
<input type="text" name="textfield">
</label>
<p>
<input name="submit" type="submit" value="submit"> <!-- changed from type="button" to type="submit"> -->
<p>
</form>

Categories