Filter SQL query by dropdown - php

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>

Related

for loop over selection option value HTML with PHP

Hi I work like loop through the selection option values with PHP instead of duplicating it, from value 500 to 510. Can you kindly show me how to do it?
<body>
<div class="form-group">
<br> <label>Job Description</label>: <b><?php echo $row['job_desc']; ?><br></b>
<select class="form-control" name="job_code">
<option value="500">System Analysis</option>
<option value="501">Programmer</option>
<option value="502">Database Designer</option>
<option value="503">Electrical Engineer</option>
<option value="504">Mechanical Engineer</option>
<option value="505">Civil Engineer</option>
<option value="506">Clerical Support</option>
<option value="507">DSS Analyst</option>
<option value="508">Application Designer</option>
<option value="509">Bio Technician</option>
<option value="510">General Support</option>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" name="update" value="Update Data">Save</button>
</div>
</body>
Employee BDJob DB
<?php
$connection = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($connection, 'amaz');
if (isset($_POST['update'])) {
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$sex = $_POST['sex'];
$emp_salary = $_POST['emp_salary'];
$dept_name = $_POST['dept_name'];
$job_code = $_POST['job_code'];
$query = "UPDATE employee
SET employee.first_name='$_POST[first_name]',employee.last_name='$_POST[last_name]',employee.sex='$_POST[sex]',employee.emp_salary='$_POST[emp_salary]',employee.dept_id='$_POST[dept_name]',employee.job_code='$_POST[job_code]'
WHERE employee.emp_num='$_POST[id]'";
$query_run = mysqli_query($connection, $query);
}
?>
You make a SELECT query that looks at the jobs table:
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'amaz';
$mysql = new mysqli($server, $user, $pass, $db);
if ($mysql->connect_error !== null) {
printf("Connect failed: %s\n", $mysql->connect_error);
exit;
}
$select = $mysql->query("SELECT * FROM jobs WHERE job_code > 409 and job_code < 511");
$jobs = [];
while ($row = $select->fetch_array(MYSQLI_ASSOC)) {
$jobs[] = $row;
}
?>
<select class="form-control" name="job_code">
<?php foreach ($jobs as $job): ?>
<option value="<?=$job['job_code']?>"><?=$job['job_desc']?></option>
<?php endforeach; ?>
</select>
This will output:
<select class="form-control" name="job_code">
<option value="500">System Analysis</option>
<option value="501">Programmer</option>
<option value="502">Database Designer</option>
...etc
</select>

Keep the value selected after fetching the data and query to insert it into database

I have this onchange event on php, if the user choose an option, it fetched the data that is connected on it. However, the page refreshes and the choice of the user disappear. Also, I cannot insert the data to database. I've tried add a form method="post" to the form attribute, but unfortunately it cannot fetch the data.
Thankyou in advance.
<?php
$dsn = 'mysql:host=localhost;dbname=admin';
$username = 'root';
$password = '';
try{
// Connect To MySQL Database
$con = new PDO($dsn,$username,$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo 'Not Connected '.$ex->getMessage();
}
$gradeassign = '';
$sectionassign = '';
function getPosts()
{
$posts = array();
$posts[3] = $_POST['sectionassign'];
$posts[4] = $_POST['gradeassign'];
return $posts;
}
if(isset($_POST['addfac']))
{
$data = getPosts();
$insertStmt = $con->prepare('INSERT INTO
facultyagain(sectionnumber,gradelevelassign)
VALUES(:sectionassign,:gradeassign)');
$insertStmt->execute(array(
':sectionassign'=> $data[3],
':gradeassign'=> $data[4],
));
if($insertStmt)
{
echo 'Data Inserted';
}
}
?>
<html>
<head>
<title>Country</title>
</head>
<body>
<form action="trial.php">
Select Your grade
<select name="gradeassign" onchange="this.form.submit()">
<option value="" disabled selected>--select--</option>
<option value="1">Grade 1</option>
<option value="2">Grade 2</option>
<option value="europe">Europe</option>
</select>
<?php
require 'connection.php';
if(isset($_GET["gradeassign"])){
$gradeassign=$_GET["gradeassign"];
$sql = "SELECT sectionassign FROM sections WHERE gradeassign='$gradeassign'";
$result = $con->query($sql);
echo "<select>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='$row[sectionassign]'>" . $row["sectionassign"]. " </option>";
}
} else { echo "<B>0 Results</B>"; }
echo "</select>";
}
?>
<BR>
<button id="addfac" name="addfac">Add Faculty</button>
</form>
</body>
</html>
You can also store the value in a variable and check to see if the option matches the variable. For example:
<option value="" disabled>--select--</option>
<option value="1" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "1") echo "checked"; ?>>Grade 1</option>
<option value="2" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "2") echo "checked"; ?>>Grade 2</option>
<option value="europe" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "europe") echo "checked"; ?>>Europe</option>
The better way to do it would be to create the whole list with a loop. Bu this should work.

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>

html form using PHP_SELF & php validation - after submit, results displayed on new page without displaying form

I am trying to create an html search form using a similar code as posted below.
When I submit the form, I want to submit to PHP_SELF
I want to use php validation code to filter the data.
When I submit the form, I cannot figure out how to get the results to post to a new page without displaying the form.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyz_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$showHtml = true;
$month = $day = $year = "";
$monthErr = $dayErr = $yearErr = "";
$errorMessage = "Oops..Please correct the item(s) highlighted in red on the form below and re-submit";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Month error & filter check code....
if (empty($_POST["month"])) {
$month = "";
} else {
$month = test_input($_POST["month"]);
if (!preg_match("/^[a-zA-Z ]*$/",$month)) {
$monthErr = "An invalid entry has been detected. Please reset this form and re-submit.";
}
}
// Day error & filter check code....
if (empty($_POST["day"])) {
$day = "";
} else {
$day = test_input($_POST["day"]);
if (!is_numeric($day)) {
$dayErr = "Day Found - An invalid entry has been detected. Please reset this form and re-submit.";
}
}
// Year error & filter check code....
if (empty($_POST["year"])) {
$year = "";
} else {
$year = test_input($_POST["year"]);
if (!is_numeric($year)) {
$yearErr = "Year Found - An invalid entry has been detected. Please reset this form and re-submit.";
}
}
if (empty($monthErr) and empty($dayErr) and empty($yearErr)) {
$showHtml = false;
$value1 = $_POST['month'];
$value2 = $_POST['day'];
$value3 = $_POST['year'];
$sql = "SELECT * FROM xyz_test_database WHERE month = ('$value1') AND day = ('$value2') AND year = ('$value3')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {echo "<br><br><h2>Search Results</h2>
<table><tr>
<th>ID</th>
<th>Time Stamp</th>
<th>Month</th>
<th>Day</th>
<th>Year</th>
</tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["id"]."</td>
<td>".$row["time_stamp"]."</td>
<td>".$row["month"]."</td>
<td>".$row["day"]."</td>
<td>".$row["year"]."</td>
</tr>";
}
echo "</table>";
} else {
echo "<p id='no_results'>Sorry - No Results Found :( </p>";
}
}
}
$conn->close();
exit ();
?>
<?php
if ($showHtml)
{
?>
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
</head>
<body>
<form name="form1" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select id="item_select" name="month">
<option value="">Select Month</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<select id="item_select" name="day">
<option value="">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<select id="item_select" name="year">
<option value="">Year</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="1975">1975</option>
</select>
<br>
<span class="error"><?php echo $monthErr;?></span>
<span class="error"><?php echo $dayErr;?></span>
<span class="error"><?php echo $yearErr;?></span>
<br>
<input type="Submit" id="submit" name="submit" value="Submit Search" style="width: 120px; color: blue;"/>
</form>
</body>
</html>
<?php
}
?>
There are a number of ways to achieve this. You can put an if statement around your html code so that it only displays if certain conditions (e.g. results aren't returned) are met.
One really simple way of doing this is to set a boolean value if results are returned. For example:
<?php
$showHtml = true;
...
if($result->num_rows > 0)
{
$showHtml = false;
...
}
...
$conn->close();
if($showHtml)
{
?>
<!DOCTYPE html>
...
</html>
<?php
}
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyz_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$showHtml = true;
$month = $day = $year = "";
$monthErr = $dayErr = $yearErr = "";
$errorMessage = "Oops..Please correct the item(s) highlighted in red on the form below and re-submit";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Month error & filter check code....
if (empty($_POST["month"])) {
$month = "";
} else {
$month = test_input($_POST["month"]);
if (!preg_match("/^[a-zA-Z ]*$/",$month)) {
$monthErr = "An invalid entry has been detected. Please reset this form and re-submit.";
}
}
// Day error & filter check code....
if (empty($_POST["day"])) {
$day = "";
} else {
$day = test_input($_POST["day"]);
if (!is_numeric($day)) {
$dayErr = "Day Found - An invalid entry has been detected. Please reset this form and re-submit.";
}
}
// Year error & filter check code....
if (empty($_POST["year"])) {
$year = "";
} else {
$year = test_input($_POST["year"]);
if (!is_numeric($year)) {
$yearErr = "Year Found - An invalid entry has been detected. Please reset this form and re-submit.";
}
}
if (empty($monthErr) and empty($dayErr) and empty($yearErr)) {
$showHtml = false;
$value1 = $_POST['month'];
$value2 = $_POST['day'];
$value3 = $_POST['year'];
$sql = "SELECT * FROM xyz_test_database WHERE month = ('$value1') AND day = ('$value2') AND year = ('$value3')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {echo "<br><br><h2>Search Results</h2>
<table><tr>
<th>ID</th>
<th>Time Stamp</th>
<th>Month</th>
<th>Day</th>
<th>Year</th>
</tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["id"]."</td>
<td>".$row["time_stamp"]."</td>
<td>".$row["month"]."</td>
<td>".$row["day"]."</td>
<td>".$row["year"]."</td>
</tr>";
}
echo "</table>";
} else {
echo "<p id='no_results'>Sorry - No Results Found :( </p>";
}
}
}
$conn->close();
exit ();
?>
<?php
if ($showHtml)
{
?>
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
</head>
<body>
<form name="form1" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select id="item_select" name="month">
<option value="">Select Month</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<select id="item_select" name="day">
<option value="">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<select id="item_select" name="year">
<option value="">Year</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="1975">1975</option>
</select>
<br>
<span class="error"><?php echo $monthErr;?></span>
<span class="error"><?php echo $dayErr;?></span>
<span class="error"><?php echo $yearErr;?></span>
<br>
<input type="Submit" id="submit" name="submit" value="Submit Search" style="width: 120px; color: blue;"/>
</form>
</body>
</html>
<?php
}
?>

PHP form validation

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>

Categories