PHP form validation - php

Below is my script that inserts data into a table. My question is only concerning form validations in php.
Here is my php code:
<?php
//Here I have defined an error variable for each of the variables in the project
$nameErr = $productErr = $priceErr = $catErr = $regionErr = "";
$product_name = $product_cond = $product_price = $product_cat = $product_region = "";
$con=mysqli_connect("localhost","*****","*****","my_project");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// here in this elseif, I check the number of characters in the field and then it is suppose to send an error (on the same page) if it does not match
elseif (strlen($_POST['product_name']) < 5 ) {
$productErr = "name is too short";
}
elseif (strlen($_POST['product_name']) > 10) {
$productErr = "name is too long";
}
elseif (empty($_POST['product_cond'])) {
$productErr = "product condition required";
}
else
{
$sql= "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES
('$_POST[product_name]','$_POST[product_cond]','$_POST[product_price]','$_POST[product_cat]','$_POST[product_region]','$_POST[Email]','$_POST[PhoneNumber]')";
if (!mysqli_query($con,$sql))
{
echo 'Error: ' . mysqli_error($con);
}
else
{
echo "1 record added";
}
}
mysqli_close($con);
?>
and here is my html page:
<html>
<body>
<h3> Please enter your product information bellow: </h3>
<form action="insert_data.php" method="post">
Product name: <input type="text" name="product_name" >
// here I added this line that is suppose to do echo the error message:
<span class="error">* <?php echo $nameErr;?></span>
Condition:
<select name="product_cond">
<option value="" >SELECT</option>
<option value="Used" >Used </option>
<option value="new" >New</option>
</select>
Category:
<select name="product_cat">
<option value="" >SELECT</option>
<option value="books" >books</option>
<option value="Computers" >Computers</option>
<option value="Hardware/Tools" >Hardware/Tools </option>
<option value="Cars" >Cars</option>
<option value="home Appliances" >home Appliances</option>
</select>
Region:
<select name="product_region">
<option value="Oulu" >Oulu</option>
<option value="Turku" >Turku</option>
<option value="Helsinki" >Helsinki </option>
<option value="Tornio" >Tornio</option>
<option value="Tampere" >Tampere</option>
<option value="Kemi" >Kemi</option>
</select>
Product price: <input type="text" name="product_price">
<input type="submit">
</form>
</body>
</html>
The problem is that this method still prevents the data to be inserted into the table but it does not give me an error instead, it just gives me a blank screen. What is the problem.
(I'm using this example provided by w3school: http://www.w3schools.com/php/showphp.asp?filename=demo_form_validation_required)

Try below code in php:
<?php
$con=mysqli_connect("localhost","*****","*****","my_project");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$error = false;
$errorMsg = "";
if (strlen($_POST['product_name']) < 5 ) {
$error = true;
$errorMsg. = "name is too short";
}
elseif (strlen($_POST['product_name']) > 10) {
$error = true;
$errorMsg. = "name is too long";
}
if (empty($_POST['product_cond'])) {
$error = true;
$errorMsg. = "product condition required<br/>";
}
if (empty($_POST['product_price'])) {
$error = true;
$errorMsg. = "product price required<br/>";
}
if (empty($_POST['product_cat'])) {
$error = true;
$errorMsg. = "product category required<br/>";
}
if (empty($_POST['product_region'])) {
$error = true;
$errorMsg. = "product region required<br/>";
}
if (empty($_POST['email'])) {
$error = true;
$errorMsg. = "email required<br/>";
}
if (empty($_POST['phone_num'])) {
$error = true;
$errorMsg. = "phone required<br/>";
}
if(!$error)
{
$sql= "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES ('$_POST[product_name]','$_POST[product_cond]','$_POST[product_price]','$_POST[product_cat]','$_POST[product_region]','$_POST[Email]','$_POST[PhoneNumber]')";
if (!mysqli_query($con,$sql))
{
echo 'Error: ' . mysqli_error($con);
}
else
{
echo "1 record added";
}
}else{
echo $errorMsg;
}
mysqli_close($con);
?>

PHP CODE
<?php
//Here I have defined an error variable for each of the variables in the project
if (isset($_POST['product_name']) && isset($_POST['product_cond']) && isset($_POST['product_price']) && isset($_POST['product_cat']) && isset($_POST['product_region']) && isset($_POST['Email']) && isset($_POST['PhoneNumber'])) {
$nameErr = $productErr = $priceErr = $catErr = $regionErr = "";
$product_name = $product_cond = $product_price = $product_cat =
$product_region = "";
$con = mysqli_connect("localhost", "*****", "*****", "my_project");
if
(mysqli_connect_errno()
) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// here in this elseif, I check the number of characters in the
field and then it is suppose to send an error(on the same page) if it
does not match
elseif (strlen($_POST['product_name']) < 5) {
$productErr = "name is too short";
} elseif (strlen($_POST['product_name']) > 10) {
$productErr = "name is too long";
} elseif (empty($_POST['product_cond'])) {
$productErr = "product condition required";
}
else {
$sql = "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES
('$_POST['product_name']','$_POST['product_cond']','$_POST['product_price']','$_POST['product_cat']','$_POST['product_region']','$_POST['Email']','$_POST['PhoneNumber']')";
if (!mysqli_query($con, $sql)) {
echo 'Error: ' . mysqli_error($con);
} else {
echo "1 record added";
} } mysqli_close($con);
}
?>
HTML
<html>
<body>
<h3> Please enter your product information bellow: </h3>
<form action="insert_data.php" method="post">
Product name: <input type="text" name="product_name" pattern="[a-zA-Z]{4,9}" required>
// here I added this line that is suppose to do echo the error message:
<span class="error">* <?php echo $nameErr;?></span>
Condition:
<select name="product_cond" required>
<option value="" >SELECT</option>
<option value="Used" >Used </option>
<option value="new" >New</option>
</select>
Category:
<select name="product_cat" required>
<option value="" >SELECT</option>
<option value="books" >books</option>
<option value="Computers" >Computers</option>
<option value="Hardware/Tools" >Hardware/Tools </option>
<option value="Cars" >Cars</option>
<option value="home Appliances" >home Appliances</option>
</select>
Region:
<select name="product_region" required>
<option value="Oulu" >Oulu</option>
<option value="Turku" >Turku</option>
<option value="Helsinki" >Helsinki </option>
<option value="Tornio" >Tornio</option>
<option value="Tampere" >Tampere</option>
<option value="Kemi" >Kemi</option>
</select>
Product price: <input type="text" name="product_price" pattern="[0-9]{0,5}" required>
<input type="submit">
</form>

Related

Undefined index in php inside selected drop down

this is the undefined error that i got
the update is working. but after i clicked the submit button, the selected dropdown gave me this error.
$row=array();
if (isset($_GET['typeid'])) {
$sql = "SELECT * FROM vehicletype WHERE id_vehicleType=" . $_GET['typeid'];
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
}
// update record
if(isset($_POST['submit'])){
$id = mysqli_real_escape_string($link,$_POST['idtype']);
$type = mysqli_real_escape_string($link, $_POST['type']);
$status = mysqli_real_escape_string($link, $_POST['status']);
$update = mysqli_real_escape_string($link, $_SESSION['idinfostaf']);
$result = mysqli_query($link, "UPDATE vehicletype SET vehicle_Type='$type', status_vehicleType='$status', updateby_vehicleType='$update' WHERE id_vehicleType=".$id);
if ($result) {
$success = "Record updated successfully!";
}
else {
$error = "Error updating record...";
}
}
i put the php code and html on the same page..below is the html
<div class="form-group">
<label>Choose Vehicle Type Status</label>
<select class="form-control" name="status" required class="form-control" value="<?php if(isset($row['status_vehicleType'])){ echo $row['status_vehicleType'];} ?>">
<option value="">Select Vehicle Type</option>
<option
value="1" <?php if ($row['status_vehicleType']==$_GET["typeid"]) { echo 'selected="selected"' ;} ?> >Enabled</option>
<option
value="0" <?php if ($row['status_vehicleType']== $_GET["typeid"]) { echo 'selected="selected"' ;} ?> >Disabled</option>
</select>
<hr>
<button type="submit" name="submit" class="btn btn-info">Submit </button>
<span class="text-success"><?php if (isset($success)) { echo $success; } ?></span>
<span class="text-danger"><?php if (isset($error)) { echo $error; } ?></span>
i used the typeid to carry the values.
Try this:
<select value="<?php if(isset($row['status_vehicleType'])){ echo $row['status_vehicleType'];} ?>">
<option value="">Select Vehicle Type</option>
<option value="1" <?php
if(isset($row['status_vehicleBrand'])) {
if ($row['status_vehicleBrand']==$_GET["typeid"]) {
echo 'Selected' ;
}
} ?> >Enabled</option>
<option value="0" <?php
if(isset($row['status_vehicleBrand'])) {
if ($row['status_vehicleBrand']==$_GET["typeid"]) {
echo 'Selected' ;
}
} ?> >Disabled</option>
</select>

PHP error submitting to SQL database

Looking for help please. I'm new to php and my course needs me to save form data to an sql database. I have the below code which creates my error message "Something went wrong". I'm studying online and my lecturer is less than useless at helping. Can anyone tell me where I am going wrong please?
My database reads and writes ok elsewhere..
<?php
$page_title = "Login Page";
session_start();
include('header.php');
require_once("validation_functions.php");
require_once('functions.php');
require_once('connection.php');
// Check if form was submitted
if (isset($_POST['submit'])) {
// Remove whitespace from beginning and end of values
$title = trim($_POST["Title"]);
$director = trim($_POST["Director"]);
$producer = trim($_POST["Producer"]);
$running_time = trim($_POST["Running"]);
$starring = trim($_POST["Starring"]);
$distributor = trim($_POST["Distributor"]);
// Escape strings and filter input to prevent SQL injection
$title = mysqli_real_escape_string($connection, $title);
$director = mysqli_real_escape_string($connection, $director);
$producer = mysqli_real_escape_string($connection, $producer);
$starring = mysqli_real_escape_string($connection, $starring);
$distributor = mysqli_real_escape_string($connection, $distributor);
$running_time = intval($running_time);
if (isset($_POST["Rel"])) { $release = $_POST["Rel"]; }
if (isset($_POST["Genre"])) { $genre = $_POST["Genre"]; }
if (isset($_POST["Rating"])) { $rating = $_POST["Rating"]; }
$form_errors = false;
// Check if fields are blank
if (is_blank($title) || is_blank($director) || is_blank($producer) || is_blank($release) || is_blank($running_time) || is_blank($starring) || is_blank($distributor)) {
$blank_message = "<p class='error-msg'>All fields are required.</p>";
$form_errors = true;
}
// Check if running time is a valid number
if (isset($running_time) && !filter_var($running_time, FILTER_VALIDATE_INT)) {
$number_message = "<p class='error-msg'>Running time is not a valid number.</p>";
$form_errors = true;
}
// Check if movie already exists
if (record_exists("SELECT * FROM Movie WHERE Movie.Title = '{$title}'")) {
$exists_message = "<p class='error-msg'>This movie already exists in the database.</p>";
$form_errors = true;
}
if ($form_errors == false) {
$insert_movie = "INSERT INTO Movie (Title, Director, Producer, Rel, Running, GenreID, Starring, Distributor, Rating) VALUES ('{$title}', '{$director}', '{$producer}', '{$release}', '{$running_time}'', '{$genre}', '{$starring}', '{$distributor}', '{$rating}')";
if (mysqli_query($connection, $insert_movie)) {
$movie_id = mysqli_insert_id($connection);
$success_message = "<p class='success-msg'>The movie has been successfully added to the database.</p>";
}
else {
$error_message = "<p class='error-msg'>Something went wrong. Please try again.</p>";
}
}
}
//php code ends here
?>
<!-- // PUT ERRORS HERE-->
<?php if (isset($blank_message)) { echo $blank_message; } ?>
<?php if (isset($number_message)) { echo $number_message; } ?>
<?php if (isset($date_message)) { echo $date_message; } ?>
<?php if (isset($exists_message)) { echo $exists_message; } ?>
<?php if (isset($success_message)) { echo $success_message; } ?>
<?php if (isset($error_message)) { echo $error_message; } ?>
<form action="<?php htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" enctype="multipart/form-data" id="movieinput">
Title:<br>
<input type="text" name="Title" placeholder="e.g. Aliens" data-validation="required" value="<?php if (isset($title)) { echo $title; } ?>"><br>
Director:<br>
<input type="text" name="Director" placeholder="e.g. Ridley Scott" data-validation="required" value="<?php if (isset($director)) { echo $director; } ?>"><br>
Producer:<br>
<input type="text" name="Producer" placeholder="e.g. Gale Ann Hurd" data-validation="required" value="<?php if (isset($producer)) { echo $producer; } ?>"><br>
Release Date:<br>
<input type="date" name="Rel" format="yyyy/mm/dd" value="<?php if (isset($date)) { echo $date; } ?>"><br>
Running Time (mins):<br>
<input type="number" pattern=".{1,3}" name="Running" placeholder="e.g. 137" data-validation="required" value="<?php if (isset($running)) { echo $running; } ?>"><br>
Genre:<br><select name="Genre" value="<?php if (isset($genre)) { echo $genre; } ?>"><br>>
<option value="drama" name="drama">Drama</option>
<option value="documentary" name ="documentary">Documentary</option>
<option value="scifi" name="scifi" selected>Sci-Fi</option>
<option value="comedy" name="comedy">Comedy</option>
<option value="biopic" name ="biopic">Biopic</option>
<option value="horror" name="horror">Horror</option>
</select><br>
Starring:<br>
<input type="text" name="Starring" placeholder="e.g. Sigourney Weaver, Michael Biehn, William Hope" value="<?php if (isset($starring)) { echo $starring; } ?>"><br>
Distributor:<br>
<input type="text" name="Distributor" placeholder="e.g. 20th Century Fox" data-validation="required" value="<?php if (isset($distributor)) { echo $distributor; } ?>"><br>
Rating:<br><select name="Rating" value="<?php if (isset($rating)) { echo $rating; } ?>"><br>>>
<option
value="one">1
</option>
<option
value="two">2
</option>
<option
value="three">3
</option>
<option
value="four">4
</option>
<option
value="five">5
</option>
</select><br>
<br>
<input type="submit" name="submit" value="Submit"/>
</form>
<script> </script>
You are using SQL database from php and using mysqli_query() function to insert which would definitely not work. You have to use PDO. to access SQL database.
Connect to SQL Server through PDO using SQL Server Driver
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=0ahUKEwjk4MS-w-HRAhUPR48KHbLaAIMQFggdMAE&url=http%3A%2F%2Fphp.net%2Fmanual%2Fen%2Fref.pdo-dblib.php&usg=AFQjCNGG9EMmNv41NHQfjhpapjqhugBYQA
> $insert_movie = "INSERT INTO Movie (Title, Director, Producer, Rel,
> Running, GenreID, Starring, Distributor, Rating) VALUES ('{$title}',
> '{$director}', '{$producer}', '{$release}', '{$running_time}'',
> '{$genre}', '{$starring}', '{$distributor}', '{$rating}')";
use this instead of
> $insert_movie = "INSERT INTO Movie (Title, Director, Producer, Rel,
> Running, GenreID, Starring, Distributor, Rating) VALUES ('$title',
> '$director', '$producer', '$release', '$running_time', '$genre',
> '$starring', '$distributor', '$rating')";
In this case, some of the below possibility will cause this issue.
Input type is mismatch with column data type in database table.
Required parameter to be used to insert into the table.
One suggestion to ensure that there is no issue in INSERT query. Just print the insert statement in browser and execute that manually in DB.
$insert_movie = "INSERT INTO Movie (Title, Director, Producer, Rel, Running, GenreID, Starring, Distributor, Rating) VALUES ('{$title}', '{$director}', '{$producer}', '{$release}', '{$running_time}'', '{$genre}', '{$starring}', '{$distributor}', '{$rating}')";
echo $insert_movie; exit;
Try this and will continue the debugging if there is no issue in insert statement.
Cheers!

Filter SQL query by dropdown

I want to filter my SQL. I made a function for that, the filter is only with dropdowns.
But this function is not working very well.
This is my function which is called on the List.php:
function getFilterList ($Category, $Price, $Language) {
$servername = "localhost";
$username_connect = "root";
$password_connect = "";
$dbname = "Product";
$link = mysqli_connect($servername, $username_connect, $password_connect, $dbname);
if (!$link) {
die('Verbindung nicht möglich : ' . mysqli_error($link) );
}
if($Category=="0") {
$filtercategory= "Hardware' OR Category='Software' OR Category='Games' OR Category='Sport' OR Category='Other";
} else if($Category=="1") {
$filtercategory="Hardware";
} else if($Category=="2") {
$filtercategory="Software";
} else if($Category=="3") {
$filtercategory="Games";
} else if($Category=="4") {
$filtercategory="Sport";
} else if($Category=="5") {
$filtercategory="Other";
}
if($Price=="0"){
$filterprice= "0' OR Price='5' OR Price='10' OR Price='15' OR Game='20' OR Price='30";
} else if($Price=="1") {
$filterprice="5";
} else if($Price=="2") {
$filterprice="10";
} else if($Price=="3") {
$filterprice="15";
} else if($Price=="4") {
$filterprice="20";
} else if($Price=="5") {
$filterprice="30";
}
if ($Language=="0") {
$filterlanguage= "German' OR Language='Englisch' OR Language='France' OR Language='Spanish";
} else if ($Language=="1") {
$filterlanguage="German";
} else if ($Language=="2") {
$filterlanguage="Englisch";
} else if ($Language=="3") {
$filterlanguage="France";
} else if ($Language=="4") {
$filterlanguage="Spanish";
}
$link = mysqli_connect($servername, $username_connect, $password_connect, $dbname);
if (!$link) {
die('Verbindung nicht möglich : ' . mysqli_error($link) );
}
$get_product = "SELECT * FROM products WHERE (ShortDescription!='' AND Category='$filtercategory' AND Price='$filterprice' AND Language='$filterlanguage') order by ID DESC";
$run_product = mysqli_query($link, $get_product);
while($row_product = mysqli_fetch_array($run_product)) {
$product_id = $row_product["ID"];
$ProuductShortDescription = $row_product["ShortDescription"];
echo "
<div id='Single_Product'>
<a href='details.php?ID=$product_id' class='ui-btn' id='ProductButton'>$ProductShortDescription</a>
</div>";
}
}
This is my Filter.php:
<form action="List.php" method="post">
<fieldset data-role="controlgroup" data-mini="true">
<select name="FilterselectCategory" id="FilterselectCategory">
<option value="0">Category</option>
<option value="1">Hardware</option>
<option value="2">Software</option>
<option value="3">Games</option>
<option value="3">Sport</option>
<option value="4">Other</option>
</select>
<select name="FilterselectPrice" id="FilterselectPrice">
<option value="0">Price</option>
<option value="1">0</option>
<option value="2">5</option>
<option value="3">10</option>
<option value="4">15</option>
<option value="5">20</option>
<option value="6">30</option>
</select>
<select name="FilterselectLanguage" id="FilterselectLanguage">
<option value="0">Language</option>
<option value="1">Englisch</option>
<option value="2">German</option>
<option value="3">France</option>
<option value="4">Spanish</option>
</select>
</fieldset>
<input type="submit" id="FilterButton" name="FilterButton" value="Filter">
</form>

this is concerning PHP and form validations

bellow you see my form validation script that I have been working on for a while. The script is suppose to check if the "Name:" is first not empty and then if it only contains letters and then insert the data. Likewise for the "Price:" it is suppose to check if it is not empty and then it's only digits. So far I have failed to make all the functions working and here are the problems as it sits right now:
in general it does not insert data to the table
regardless says price is required (even if the price is given)
when there is given numbers in the name field, there is no error
and here is the script:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$con=mysqli_connect("localhost","xxxxx","xxxxx","my_project");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// define variables and set to empty values
$nameErr = $priceErr = $catErr = $condErr = $regionErr = "";
$product_name = $product_price = $product_cat = $product_cond = $product_region = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["product_name"]))
{
$nameErr = "Name is required";
}
else if (!preg_match("/^[a-zA-Z ]*$/",$product_name))
{
$nameErr = "Only letters and white space allowed";
}
if (empty ($_POST ["product_price"]))
{
$priceErr = "Price is required";
}
else if(!ctype_digit($product_price))
{
$priceErr = "Price is required";
}
else
{
$product_name = test_input($_POST["product_name"]);
$product_price = test_input($_POST["product_price"]);
$sql= "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES
('$_POST[product_name]','$_POST[product_cond]','$_POST[product_price]','$_POST[product_cat]','$_POST[product_region]','$_POST[Email]','$_POST[PhoneNumber]')";
if (!mysqli_query($con,$sql))
{
echo 'Error: ' . mysqli_error($con);
}
else
{
echo "1 record added";
}
mysqli_close($con);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="product_name" value="<?php echo $product_name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
price: <input type="text" name="product_price" value="<?php echo $product_price;?>">
<span class="error">* <?php echo $priceErr;?></span>
<br><br>
Condition:
<select name="product_cond" required >
<option value="" >SELECT</option>
<option value="Used" >Used </option>
<option value="new" >New</option>
</select>
Category:
<select name="product_cat" required >
<option value="" >SELECT</option>
<option value="books" >books</option>
<option value="Computers" >Computers</option>
<option value="Hardware/Tools" >Hardware/Tools </option>
<option value="Cars" >Cars</option>
<option value="home Appliances" >home Appliances</option>
</select>
Region:
<select name="product_region" required >
<option value="" >SELECT</option>
<option value="Oulu" >Oulu</option>
<option value="Turku" >Turku</option>
<option value="Helsinki" >Helsinki </option>
<option value="Tornio" >Vaasa</option>
<option value="Tampere" >Tampere</option>
<option value="Kemi" >Kemi</option>
<input type="submit">
</form>
</body>
and here is the example that I have used and modified:
http://www.w3schools.com/php/showphp.asp?filename=demo_form_validation_special
I'd suggest to use an array of errors instead of variables.
Then you should access the variables you send by the form like $_POST['variable']
Try this code:
$errors = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["product_name"])) {
$errors['name'] = "Name is required";
} else if (!preg_match("/^[a-zA-Z ]*$/", $_POST['product_name'])) {
$errors['name'] = "Only letters and white space allowed";
}
if (empty($_POST ["product_price"])) {
$errors['price'] = "Price is required";
} else if (!ctype_digit($_POST['product_price'])) {
$errors['price'] = "Price is required";
}
if(count($errors) == 0){
$product_name = test_input($_POST["product_name"]);
$product_price = test_input($_POST["product_price"]);
$sql = "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES
('$_POST[product_name]','$_POST[product_cond]','$_POST[product_price]','$_POST[product_cat]','$_POST[product_region]','$_POST[Email]','$_POST[PhoneNumber]')";
if (!mysqli_query($con, $sql)) {
echo 'Error: ' . mysqli_error($con);
} else {
echo "1 record added";
}
}
}

updating sql table for selected check box values

I dynamically create table rows with checkboxes. Check a few of them and then perform and update query on the selected ones. But the problem I face is that only the first selected record gets updated even though I have used foreach loop.
Following is the code.
<?php
$checkbox = $_POST['pr'];
$year = $_POST['promoteyearselect1'];
$semester = $_POST['promotesemselect1'];
# $db = mysql_connect("abc", "abc", "");
mysql_select_db("abc");
foreach($checkbox as $value){
if(isset($checkbox)){
if(($semester%2)==0) {
$strSQL = "UPDATE student SET year='".++$year."', semester='".++$semester."' WHERE enrollment='".$value."'";
$rs = mysql_query($strSQL);
if($rs){
echo 'Promotion Successful';
header("location:page1.php");
echo '<script> alert("Promotion Successful");</script>';
}
else echo "Sorry, but that did not work. ";
}
else{
$strSQL = "UPDATE student SET semester=".++$semester."' WHERE enrollment='".$value."'";
$rs = mysql_query($strSQL);
if($rs){
echo 'Promotion Successful';
header("location:page1.php");
echo '<script> alert("Promotion Successful");</script>';
}
else echo "Sorry, but that did not work. ";
}
}
}
mysql_close($db);
?>
Even though I use the foreach loop to get through the array of checkboxes, still only the first checked record gets updated.
This is the html part
<div class="dropdown dropdown-dark">
<select name="promoteyearselect1" id="promoteyearselect1" class="dropdown-select" onfocus="showhidephdmenu()" form="promotionform" required>
<option value="">Select an option</option>
<div id="yearselect1">
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
<option value="4">4th</option>
<option value="5">5th</option>
</div>
</option>
</select>
</div>
<div class="dropdown dropdown-dark">
<select name="promotesemselect1" id="promotesemselect1" class="dropdown-select" form="promotionform" required>
<option value="">Select an option</option>
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
<option value="4">4th</option>
<option value="5">5th</option>
<option value="6">6th</option>
<option value="7">7th</option>
<option value="8">8th</option>
<option value="9">9th</option>
<option value="10">10th</option>
</select>
</div>
<button id="promotego" class="login-button" style=" position:relative; padding: 0 0 0; " onclick="getpromotestudents()"></button>
</div>
<form id="promotionform" action="promotestudents.php" method="POST">
<div id="promoteresults">
The results will show up here..!!
</div>
<div style=" position:relative; margin-top:10px; padding-left:44%;">
<input type="submit" value="Promoted" class="button black"></input>
Passed Out
</div>
</form>
This is the PHP that gets the records and generates checkboxes.
$i=1;
while($r = mysql_fetch_array($rs)){
echo "<tr>";
echo "<td class='promotetabledata'>".$r[7]."</td>";
echo "<td class='promotetabledata'>".$r[6]."</td>";
echo "<td class='promotetabledata'><input type='checkbox' name='pr[]' value='".$r[7]."'/></td>";
echo "</tr>";
$i++;
}
Here is the modified code that finally worked for me, I added spaces in the if($semester % 2 != 0)
<?php
$checkbox = $_POST['pr'];
$year = $_POST['promoteyearselect1'] + 1 ;
$semester = $_POST['promotesemselect1'] + 1;
$con = mysqli_connect("localhost","root","","university") or die("Error " . mysqli_error($con));
foreach($checkbox as $value){
if(isset($checkbox)){
// echo $value;
if( $semester % 2 != 0) {
// echo $value;
$strSQL = "UPDATE student SET year='".$year."', semester='".$semester."' WHERE enrollment='".$value."'";
$rs = mysqli_query($con, $strSQL);
if($rs){
echo 'Promotion Successful';
header("location:page1.php");
echo '<script> alert("Promotion Successful");</script>';
}
else echo "Sorry, but that did not work. ";
}
else{
$strSQL = "UPDATE student SET semester='".$semester."' WHERE enrollment='".$value."'";
$rs = mysqli_query($con, $strSQL);
if($rs){
echo 'Promotion Successful';
header("location:page1.php");
echo '<script> alert("Promotion Successful");</script>';
}
else echo "Sorry, but that did not work. ";
}
}
}
mysqli_close($con);
?>
I didn't found any checkbox with name 'pr' in your code..If there is any ..please make it an array and try
like <input type="checkbox" name="pr[]">

Categories