PHP code not working (Not inserting data into database) - php

I am trying to process a form which will insert data into database, but it is inserting anything in database. I am trying this since couple of days...but got no solution....it is also not showing any error also..please guide....asap...
<?php
if(isset($_POST['submit'])){
$generic_drug_name = $_POST['generic_drug_name'];
$brand_drug_name = $_POST['brand_drug_name'];
$manufacturer_name = $_POST['manufacturer_name'];
$type = $_POST['type'];
$price = $_POST['price'];
}else{
$generic_drug_name = '';
$brand_drug_name = '';
$manufacturer_name = '';
$type = '';
$price = '';
}
$errors = '';
$errors['generic_drug_nameErr'] = '';
$errors['brand_drug_nameErr'] = '';
$errors['manufacturer_nameErr'] = '';
$errors['typeErr'] = '';
$errors['priceErr'] = '';
?>
<body>
<header>
<?php echo navigation(); ?>
</header>
<section>
<div id="envelope">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["generic_drug_name"])) {
$errors['generic_drug_nameErr'] = "Name is required";
}else{
$generic_drug_name = test_input($_POST["generic_drug_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$generic_drug_name)) {
$errors['generic_drug_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["brand_drug_name"])) {
$errors['brand_drug_nameErr'] = "Name is required";
}else{
$brand_drug_name = test_input($_POST["brand_drug_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$brand_drug_name)) {
$errors['brand_drug_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["manufacturer_name"])) {
$errors['manufacturer_nameErr'] = "Name is required";
}else{
$manufacturer_name = test_input($_POST["manufacturer_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$manufacturer_name)) {
$errors['manufacturer_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["type"])) {
$errors['typeErr'] = "Type is required";
} else {
$type = test_input($_POST["type"]);
// check if e-mail address is well-formed
if (!preg_match("/^[a-zA-Z ]*$/",$type)) {
$errors['typeErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["price"])) {
$errors['priceErr'] = "";
} else {
$price = test_input($_POST["price"]);
// check if e-mail address is well-formed
if (!preg_match("/^[0-9\_]{1,4}/",$price)) {
$errors['priceErr'] = "Invalid price format";
}
}
}
?>
<center><h1>Add a new brand drug</h1></center><br>
<label>Generic Drug Name</label><span class="error">* </span><span class="text"><?php echo $errors['generic_drug_nameErr'];?></span>
<input type="text" name="generic_drug_name" placeholder="Enter Generic drug Names" value="<?php echo htmlspecialchars($generic_drug_name); ?>" width="100px;"/>
<label>Brand Drug Name</label><span class="error">* </span><span class="text"><?php echo $errors['brand_drug_nameErr'];?></span>
<input type="text" name="brand_drug_name" placeholder="Amlokind" autofocus="autofocus" value="<?php echo htmlspecialchars($brand_drug_name); ?>" width="100px;">
<label>Manufacturer</label><span class="error">* </span><span class="text"><?php echo $errors['manufacturer_nameErr'];?></span>
<input type="text" name="manufacturer_name" placeholder="Glaxo Smithkline Pharmaceuticals Pvt. Ltd." autofocus="autofocus" value="<?php echo htmlspecialchars($manufacturer_name); ?>">
<label>Type</label><span class="error">* </span><span class="text"><?php echo $errors['typeErr'];?></span>
<input type="text" name="type" placeholder="Tablet" autofocus="autofocus" value="<?php echo htmlspecialchars($type); ?>">
<label>Price</label><span class="error">* </span><span class="text"><?php echo $errors['priceErr'];?></span>
<input type="text" name="price" placeholder="10.45" autofocus="autofocus" value="<?php echo htmlspecialchars($price); ?>" >
<input type="submit" name = "submit" value="Add" id="submit"/>
</form>
</div>
<?php
if(isset($_POST['submit'])){
/*$generic_drug_name = $_POST['generic_drug_name'];
$brand_drug_name = $_POST['brand_drug_name'];
$manufacturer_name = $_POST['manufacturer_name'];
$type = $_POST['type'];
$price = $_POST['price'];*/
if(empty($errors)){
$safe_generic_drug_name = strtoupper($generic_drug_name);
$safe_brand_drug_name = strtoupper($brand_drug_name);
$safe_manufacturer_name = ucwords($manufacturer_name);
$safe_type = ucfirst($type);
$safe_price = $price;
$query = "INSERT INTO brand_generic.brand_drug (drug_id, brand_drug_name, manufacturer, type, price)
SELECT id, '{$safe_brand_drug_name}','{$safe_manufacturer_name}', '{$safe_type}', {$safe_price}
FROM brand_generic.generic_drug
WHERE generic_drug_name = '{$safe_generic_drug_name}';";
//INSERT INTO brand_generic.brand_drug (drug_id, brand_drug_name, manufacturer, type, price) VALUES ((SELECT id FROM brand_generic.generic_drug WHERE generic_drug_name = 'AMLODIPINE'), 'ZODIPINE', 'Zorex Pharma Pvt Ltd', 'Tablet', 10);
if(!$query){
die(mysqli_error());
}
$result = mysqli_query($connection, $query);
var_dump($result);
if($result){
$_SESSION["message"] = "Successfully subject created";
//redirect_to("manage_content.php");
echo $_SESSION["message"];
}else{
$_SESSION["message"] = "Sorry, subject couldn't be created";
//redirect_to("new_subject.php");
echo $_SESSION["message"];
}
}
}
?>
This code is also not showing any error....so that's why I can't tell you what's wrong here......but it's not working...that's all I can say right now....Thank You...:)
Hello everyone once again, thanks for your suggestion, but it didn't work for me....but when I put
if(!empty($errors)){
instead of
if(empty($errors)){
it works....it should not work, right?...because it will take any data and insert it into database..if not please guide me....Thank you to all...:)

You cant use set a session after starting printing to browser.
so move
if(isset($_POST['submit'])){
to the top of page, before the HTML.

It shows a debug error message like follows.
Fatal error: Call to undefined function navigation() in /var/www/poc.php on line 25
It mean the function navigation() is used but not created any where in the script. And fatal error won't let the script to further proceed. So it is a blocking point
At least include following line at top of PHP block will avoid the error
<?php
function navigation(){
return 1;
}
?>
Additionally if you want to see the error message on your server use following two lines on the top of the script.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>

Related

HTML form disappears upon submission

I am working on a project for school and I can't seem to figure out what is wrong with my html/php page.
For the record, I am making an html page with php and it is connected to an Oracle database.
I am trying to add a Person to the Person table but when I type in the information and click submit the form (the entire body of the page) completely disappears and the record is not added to the table. I have been looking online all day for an answer and it still does not work.
My code:
<DOCTYPE HTML>
<html>
<head>
<font size="6">Schedules</font> <font size="6">Passengers</font> <font size="6">Add Passenger</font> <font size="6">Remove Passenger</font><br>
______________________________________________________________________________________________________________________________________________
<h1>Add Passenger</h1>
</head>
<body>
<br><br>
<?php
$passengerID = $passengerFName = $passengerLName = $carNo = $seatNo = $trainID = $tName = "";
$passengerIDErr = $passengerFNameErr = $passengerLNameErr = $carNoErr = $seatNoErr = $trainIDErr = $tNameErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["passengerFName"])) {
$passengerFNameErr = "First Name is required";
} else {
$passengerFName = test_inpit($_POST["passengerFName"]);
if (!preg_match("/^[a-zA-Z ]*$/",$passengerFName)) {
$passengerFNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["passengerLName"])) {
$passengerLNameErr = "Last Name is required";
} else {
$passengerLName = test_inpit($_POST["passengerLName"]);
if (!preg_match("/^[a-zA-Z ]*$/",$passengerLName)) {
$passengerLNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["carNo"])) {
$carNoErr = "Car Number is required";
} else {
$carNo = test_inpit($_POST["carNo"]);
if (!is_numeric($carNo)) {
$carNoErr = "Only numbers allowed";
}
}
if (empty($_POST["seatNo"])) {
$seatNoErr = "Seat Number is required";
} else {
$seatNo = test_inpit($_POST["seatNo"]);
if (!is_numeric($seatNo)) {
$seatNoErr = "Only numbers allowed";
}
}
if (empty($_POST["tName"])) {
$tNameErr = "Train Name is required";
} else {
$tName = test_inpit($_POST["tName"]);
if (!preg_match("/^[a-zA-Z ]*$/",$tName)) {
$tNameErr = "Only letters and white space allowed";
}
}
$passengerID = test_input($_POST["passengerID"]);
if (!is_numeric($passengerID)) {
$passengerIDErr = "Only letters and white space allowed";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter all information for the passenger<br>
<b>First Name:</b> <input type="text" name="passengerFName" value="<?php echo $passengerFName;?>">
<span class="error">* <?php echo $passengerFNameErr;?></span>
<br><br>
<b>Last Name:</b> <input type="text" name="passengerLName" value="<?php echo $passengerLName;?>">
<span class="error">* <?php echo $passengerLNameErr;?></span>
<br><br>
<b>Car Number:</b> <input type="text" name="carNo" value="<?php echo $carNo;?>">
<span class="error">* <?php echo $carNoErr;?></span>
<br><br>
<b>Seat Number:</b> <input type="text" name="seatNo" value="<?php echo $seatNo"?>">
<span class="error">* <?php echo $seatNoErr;?></span>
<br><br>
<b>Train Name:</b> <input type="text" name="tName" value="<?php echo $tName"?>">
<span class="error">* <?php echo $tNameErr;?></span>
<br><br>
<input type="submit">
<br><br><br>
<?php
$conn = oci_connect('username', 'password', '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=db1.chpc.ndsu.nodak.edu)(Port=1521)))(CONNECT_DATA=(SID=cs)))');
$query = 'SELECT MAX(personID)
FROM Person';
$stid = oci_parse($conn,$query);
oci_execute($stid,OCI_DEFAULT);
//iterate through each row
while ($row = oci_fetch_array($stid,OCI_ASSOC))
{
//iterate through each item in the row and echo it
foreach ($row as $item)
{
$passengerID = $item + 1;
}
}
oci_free_statement($stid);
oci_close($conn);
?>
<?php
$conn = oci_connect('username', 'password', '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=db1.chpc.ndsu.nodak.edu)(Port=1521)))(CONNECT_DATA=(SID=cs)))');
$query = 'SELECT trainID
FROM Train
WHERE tName = \''. $tName. '\'';
$stid = oci_parse($conn,$query);
$c1 = oci_execute($stid,OCI_DEFAULT);
if ($c1 === FALSE) {
Echo "Error! Train name does not exist";
}
//iterate through each row
while ($row = oci_fetch_array($stid,OCI_ASSOC))
{
//iterate through each item in the row and echo it
foreach ($row as $item)
{
$trainID = $item;
}
}
oci_free_statement($stid);
oci_close($conn);
?>
<?php
$conn = oci_connect('username', 'password', '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=db1.chpc.ndsu.nodak.edu)(Port=1521)))(CONNECT_DATA=(SID=cs)))');
$query = 'INSERT INTO Person (personID, fname, lname, carNo, seatNo, trainID)
VALUES (\''. $passengerID. '\', \''. $passengerFName. '\', \''. $passengerLName. '\', \''. $carNo. '\', \''. $seatNo. '\', \''. $trainID. '\')';
$stid = oci_parse($conn,$query);
$c2 = oci_execute($stid,OCI_COMMIT_ON_SUCCESS);
if ($c2 === FALSE) {
Echo "Error! Record was not added. Please check the information and try again";
}
elseif ($c2 === TRUE) {
Echo "Success! Passenger was added to the system";
}
oci_free_statement($stid);
oci_close($conn);
?>
</form>
</body>
</html>
Any help would be great. Thanks.

PHP ignoring if statements

I am having a very weird problem here, my if else statements just get ignored after I submit the form and all values entered or not entered goes through to the database.
Firstly, I pre populate all fields with info submitted during registration then users can edit and change their info - this works fine but I decided to add it as I don't know whether it might have a hand in this mystery error.
Here's my code to retrieve details, the variables holding retrieved values are echoed in their respective fields in the form.
<?php
include("connect.php");
$results = $conn->query("SELECT username, first_name,last_name, email,phone,address FROM users WHERE email='$user_logged'");
while ($row = $results->fetch_assoc()) {
$u_name = $row['username'];
$f_name = $row['first_name'];
$l_name = $row['last_name'];
$email = $row['email'];
$phone = $row['phone'];
$address = $row['address'];
}
$results->free();
$conn->close();
?>
It's not checking for empty fields. Functions test_input and preg_match do not work alsko. The form just submits and database gets updated.
I have spent 2 days going through to look for where the error might be but I can't detect it.
<?php
$user_logged = $_SESSION['logged_in'];
if (isset($_POST['btnUpdate'])) {
include("connect.php");
$phoneErr = $f_nameErr = $l_nameErr = "";
$user_email = $first_name = $last_name = $phone_upadate = $address_updated = "";
if (empty($_POST["fname"])) {
$f_nameErr = "First Name is required";
} else {
$first_name = test_input($_POST["fname"]);
if (!preg_match("/^[a-zA-Z ]*$/", $first_name)) {
$f_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["lname"])) {
$l_nameErr = "Last Name is required";
} else {
$last_name = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z ]*$/", $last_name)) {
$l_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone No is required";
} else {
$phone_upadate = test_input($_POST['phone']);
if (!preg_match("/^[0-9]{0,18}$/", $phone_upadate)) {
$phoneErr = "Only numbers and white space allowed";
}
}
$user_email = $_POST['email'];
$address_updated = $_POST['txtaddress'];
$results = $conn->query("UPDATE users SET
first_name='$first_name',last_name='$last_name',
email='$user_email',phone='$phone_upadate',
address='$address_updated'
WHERE email='$user_logged'");
if ($results) {
header("Location: edit-info.php");
} else {
print 'Error : (' . $conn->errno . ') ' . $conn->error;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Here is my html code
<form action="edit-info.php" method="POST">
<?php $username_error="can't be changed"; ?>
<p>Username</p>
<p><input type="text" name="username" id="txtuser" value="<?php echo $u_name; ?>" readonly></input><span id="error"><?php echo $username_error?></span></p>
<p>First Name</p>
<p><input type="text" name="fname" id="txtuser" value="<?php echo $f_name; ?>"></input><span id="error"><?php echo $f_nameErr;?></span></p>
<p>Last Name</p>
<p><input type="text" name="lname" id="txtuser" value="<?php echo $l_name; ?>" ></input><span id="error"><?php echo $l_nameErr;?></span></p>
<p>Email</p>
<p> <input type="text" name="email" id="txtuser" value="<?php echo $email; ?>" readonly></input><span id="error"><?php echo $f_nameErr;?></span></p>
<p>Phone</p>
<p><input type="text" name="phone" id="txtuser" value="<?php echo $phone; ?> " ></input></p>
<span id="error"><?php echo $phoneErr;?></span>
<p>Address</p>
<p><textarea id="txtaddress" name="txtaddress" cols="40" rows="10" ><?php echo $address; ?></textarea></p>
<p><input type="submit" name="btnUpdate" value="UPDATE" /></p>
</form>
You need to check the values of $phoneErr, $f_nameErr, $l_nameErr before you proceed UPDATE like this
if(empty($phoneErr) && empty($f_nameErr) && empty($l_nameErr)){
$results = $conn->query("UPDATE users SET first_name='$first_name',last_name='$last_name', email='$user_email',phone='$phone_upadate',address='$address_updated' WHERE email='$user_logged'");
}
Because when you have any validation error in empty or preg_match you are updating these values. And without checking these $phoneErr, $f_nameErr, $l_nameErr variables you are proceeding to UPDATE
You could try replacing
"/^[a-zA-Z ]*$/"
with
"/^[a-zA-Z ]+$/"
Notice we are replacing the multiplication sign with a summation sign.

PHP MySQL code not inserting data into database

I am trying to process a form which will insert data into database, but it is inserting nothing in database. I am trying this for a couple of days, but got no solution. It is also not showing any error also.
<?php
if(isset($_POST['submit'])){
$generic_drug_name = $_POST['generic_drug_name'];
$brand_drug_name = $_POST['brand_drug_name'];
$manufacturer_name = $_POST['manufacturer_name'];
$type = $_POST['type'];
$price = $_POST['price'];
}else{
$generic_drug_name = '';
$brand_drug_name = '';
$manufacturer_name = '';
$type = '';
$price = '';
}
$errors = '';
$errors['generic_drug_nameErr'] = '';
$errors['brand_drug_nameErr'] = '';
$errors['manufacturer_nameErr'] = '';
$errors['typeErr'] = '';
$errors['priceErr'] = '';
?>
<body>
<header>
<?php echo navigation(); ?>
</header>
<section>
<div id="envelope">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["generic_drug_name"])) {
$errors['generic_drug_nameErr'] = "Name is required";
}else{
$generic_drug_name = test_input($_POST["generic_drug_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$generic_drug_name)) {
$errors['generic_drug_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["brand_drug_name"])) {
$errors['brand_drug_nameErr'] = "Name is required";
}else{
$brand_drug_name = test_input($_POST["brand_drug_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$brand_drug_name)) {
$errors['brand_drug_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["manufacturer_name"])) {
$errors['manufacturer_nameErr'] = "Name is required";
}else{
$manufacturer_name = test_input($_POST["manufacturer_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$manufacturer_name)) {
$errors['manufacturer_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["type"])) {
$errors['typeErr'] = "Type is required";
} else {
$type = test_input($_POST["type"]);
// check if e-mail address is well-formed
if (!preg_match("/^[a-zA-Z ]*$/",$type)) {
$errors['typeErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["price"])) {
$errors['priceErr'] = "";
} else {
$price = test_input($_POST["price"]);
// check if e-mail address is well-formed
if (!preg_match("/^[0-9\_]{1,4}/",$price)) {
$errors['priceErr'] = "Invalid price format";
}
}
}
?>
<center><h1>Add a new brand drug</h1></center><br>
<label>Generic Drug Name</label><span class="error">* </span><span class="text"><?php echo $errors['generic_drug_nameErr'];?></span>
<input type="text" name="generic_drug_name" placeholder="Enter Generic drug Names" value="<?php echo htmlspecialchars($generic_drug_name); ?>" width="100px;"/>
<label>Brand Drug Name</label><span class="error">* </span><span class="text"><?php echo $errors['brand_drug_nameErr'];?></span>
<input type="text" name="brand_drug_name" placeholder="Amlokind" autofocus="autofocus" value="<?php echo htmlspecialchars($brand_drug_name); ?>" width="100px;">
<label>Manufacturer</label><span class="error">* </span><span class="text"><?php echo $errors['manufacturer_nameErr'];?></span>
<input type="text" name="manufacturer_name" placeholder="Glaxo Smithkline Pharmaceuticals Pvt. Ltd." autofocus="autofocus" value="<?php echo htmlspecialchars($manufacturer_name); ?>">
<label>Type</label><span class="error">* </span><span class="text"><?php echo $errors['typeErr'];?></span>
<input type="text" name="type" placeholder="Tablet" autofocus="autofocus" value="<?php echo htmlspecialchars($type); ?>">
<label>Price</label><span class="error">* </span><span class="text"><?php echo $errors['priceErr'];?></span>
<input type="text" name="price" placeholder="10.45" autofocus="autofocus" value="<?php echo htmlspecialchars($price); ?>" >
<input type="submit" name = "submit" value="Add" id="submit"/>
</form>
</div>
<?php
if(isset($_POST['submit'])){
/*$generic_drug_name = $_POST['generic_drug_name'];
$brand_drug_name = $_POST['brand_drug_name'];
$manufacturer_name = $_POST['manufacturer_name'];
$type = $_POST['type'];
$price = $_POST['price'];*/
if(empty($errors)){
$safe_generic_drug_name = strtoupper($generic_drug_name);
$safe_brand_drug_name = strtoupper($brand_drug_name);
$safe_manufacturer_name = ucwords($manufacturer_name);
$safe_type = ucfirst($type);
$safe_price = $price;
$query = "INSERT INTO brand_generic.brand_drug (drug_id, brand_drug_name, manufacturer, type, price)
SELECT id, '{$safe_brand_drug_name}','{$safe_manufacturer_name}', '{$safe_type}', {$safe_price}
FROM brand_generic.generic_drug
WHERE generic_drug_name = '{$safe_generic_drug_name}';";
//INSERT INTO brand_generic.brand_drug (drug_id, brand_drug_name, manufacturer, type, price) VALUES ((SELECT id FROM brand_generic.generic_drug WHERE generic_drug_name = 'AMLODIPINE'), 'ZODIPINE', 'Zorex Pharma Pvt Ltd', 'Tablet', 10);
if(!$query){
die(mysqli_error());
}
$result = mysqli_query($connection, $query);
var_dump($result);
if($result){
$_SESSION["message"] = "Successfully subject created";
//redirect_to("manage_content.php");
echo $_SESSION["message"];
}else{
$_SESSION["message"] = "Sorry, subject couldn't be created";
//redirect_to("new_subject.php");
echo $_SESSION["message"];
}
}
}
?>
This code is also not showing any error....so that's why I can't tell you what's wrong here.......but when I put
if(!empty($errors)){
instead of
if(empty($errors)){
This works - it should not work, right? Because it will take any data and insert it into database.
That's because you always fill your $errors array with (empty) strings. Try this:
$errors = array();
Instead of this:
$errors = '';
$errors['generic_drug_nameErr'] = '';
$errors['brand_drug_nameErr'] = '';
$errors['manufacturer_nameErr'] = '';
$errors['typeErr'] = '';
$errors['priceErr'] = '';

Mysql INSERT SUBQUERY not working

Can anyone tell me what's wrong with this query
$query = "
INSERT INTO brand_generic.brand_drug (
drug_id, brand_drug_name, manufacturer, type, price
) VALUES (
(SELECT id FROM brand_generic.generic_drug WHERE generic_drug_name = '{$safe_generic_drug_name}'), '{$safe_brand_drug_name}', '{$safe_manufacturer_name}', '{$safe_type}', {$safe_price}
);";
It's not showing any error, but it's also not inserting into database from PHP file but when I do it manually through phpmyadmin it works, I just put the actual value in place of variable.
I don't think there is any wrong in my query but still it is not inserting data in database, so i think I should put whole content of file here......
<?php
if(isset($_POST['submit'])){
$generic_drug_name = $_POST['generic_drug_name'];
$brand_drug_name = $_POST['brand_drug_name'];
$manufacturer_name = $_POST['manufacturer_name'];
$type = $_POST['type'];
$price = $_POST['price'];
}else{
$generic_drug_name = '';
$brand_drug_name = '';
$manufacturer_name = '';
$type = '';
$price = '';
}
$errors = '';
$errors['generic_drug_nameErr'] = '';
$errors['brand_drug_nameErr'] = '';
$errors['manufacturer_nameErr'] = '';
$errors['typeErr'] = '';
$errors['priceErr'] = '';
?>
<body>
<header>
<?php echo navigation(); ?>
</header>
<section>
<div id="envelope">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["generic_drug_name"])) {
$errors['generic_drug_nameErr'] = "Name is required";
}else{
$generic_drug_name = test_input($_POST["generic_drug_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$generic_drug_name)) {
$errors['generic_drug_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["brand_drug_name"])) {
$errors['brand_drug_nameErr'] = "Name is required";
}else{
$brand_drug_name = test_input($_POST["brand_drug_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$brand_drug_name)) {
$errors['brand_drug_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["manufacturer_name"])) {
$errors['manufacturer_nameErr'] = "Name is required";
}else{
$manufacturer_name = test_input($_POST["manufacturer_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$manufacturer_name)) {
$errors['manufacturer_nameErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["type"])) {
$errors['typeErr'] = "Type is required";
} else {
$type = test_input($_POST["type"]);
// check if e-mail address is well-formed
if (!preg_match("/^[a-zA-Z ]*$/",$type)) {
$errors['typeErr'] = "Only letters and white space allowed";
}
}
if (empty($_POST["price"])) {
$errors['priceErr'] = "";
} else {
$price = test_input($_POST["price"]);
// check if e-mail address is well-formed
if (!preg_match("/^[0-9\_]{1,4}/",$price)) {
$errors['priceErr'] = "Invalid price format";
}
}
}
?>
<center><h1>Add a new brand drug</h1></center><br>
<label>Generic Drug Name</label><span class="error">* </span><span class="text"><?php echo $errors['generic_drug_nameErr'];?></span>
<input type="text" name="generic_drug_name" placeholder="Enter Generic drug Names" value="<?php echo htmlspecialchars($generic_drug_name); ?>" width="100px;"/>
<label>Brand Drug Name</label><span class="error">* </span><span class="text"><?php echo $errors['brand_drug_nameErr'];?></span>
<input type="text" name="brand_drug_name" placeholder="Amlokind" autofocus="autofocus" value="<?php echo htmlspecialchars($brand_drug_name); ?>" width="100px;">
<label>Manufacturer</label><span class="error">* </span><span class="text"><?php echo $errors['manufacturer_nameErr'];?></span>
<input type="text" name="manufacturer_name" placeholder="Glaxo Smithkline Pharmaceuticals Pvt. Ltd." autofocus="autofocus" value="<?php echo htmlspecialchars($manufacturer_name); ?>">
<label>Type</label><span class="error">* </span><span class="text"><?php echo $errors['typeErr'];?></span>
<input type="text" name="type" placeholder="Tablet" autofocus="autofocus" value="<?php echo htmlspecialchars($type); ?>">
<label>Price</label><span class="error">* </span><span class="text"><?php echo $errors['priceErr'];?></span>
<input type="text" name="price" placeholder="10.45" autofocus="autofocus" value="<?php echo htmlspecialchars($price); ?>" >
<input type="submit" name = "submit" value="Add" id="submit"/>
</form>
</div>
<?php
if(isset($_POST['submit'])){
/*$generic_drug_name = $_POST['generic_drug_name'];
$brand_drug_name = $_POST['brand_drug_name'];
$manufacturer_name = $_POST['manufacturer_name'];
$type = $_POST['type'];
$price = $_POST['price'];*/
if(empty($errors)){
$safe_generic_drug_name = strtoupper($generic_drug_name);
$safe_brand_drug_name = strtoupper($brand_drug_name);
$safe_manufacturer_name = ucwords($manufacturer_name);
$safe_type = ucfirst($type);
$safe_price = $price;
$query = "INSERT INTO brand_generic.brand_drug (drug_id, brand_drug_name, manufacturer, type, price)
SELECT id, '{$safe_brand_drug_name}','{$safe_manufacturer_name}', '{$safe_type}', {$safe_price}
FROM brand_generic.generic_drug
WHERE generic_drug_name = '{$safe_generic_drug_name}';";
//INSERT INTO brand_generic.brand_drug (drug_id, brand_drug_name, manufacturer, type, price) VALUES ((SELECT id FROM brand_generic.generic_drug WHERE generic_drug_name = 'AMLODIPINE'), 'ZODIPINE', 'Zorex Pharma Pvt Ltd', 'Tablet', 10);
if(!$query){
die(mysqli_error());
}
$result = mysqli_query($connection, $query);
var_dump($result);
if($result){
$_SESSION["message"] = "Successfully subject created";
//redirect_to("manage_content.php");
echo $_SESSION["message"];
}else{
$_SESSION["message"] = "Sorry, subject couldn't be created";
//redirect_to("new_subject.php");
echo $_SESSION["message"];
}
}
}
?>
Sorry guys, but since morning I am trying to find error but I got nothing...please help me and don't get angry if there is a small-tiny error....thank you everyone.... :)
INSERT INTO brand_generic.brand_drug (drug_id, brand_drug_name, manufacturer, type, price)
SELECT id, '{$safe_brand_drug_name}','{$safe_manufacturer_name}', '{$safe_type}', {$safe_price}
FROM brand_generic.generic_drug
WHERE generic_drug_name = '{$safe_generic_drug_name}'
try this one instead:
INSERT INTO brand_generic.brand_drug (drug_id, brand_drug_name, manufacturer, type, price) SELECT ((SELECT id FROM brand_generic.generic_drug WHERE generic_drug_name = '{$safe_generic_drug_name}'), '{$safe_brand_drug_name}', '{$safe_manufacturer_name}', '{$safe_type}', {$safe_price});
YOu can't run a select like that. There's a dedicated
INSERT INTO ...
SELECT ... FROM
syntax for that, and you're probably vulnerable to sql injection attacks on top of that.

PHP Form submitting to MySQL whether validation conditions are met or not

My php self-validating form is submitting to sql database whether the characters entered into form fields are appropriate or not...How do stop it from submitting until the conditions for each form field are met?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>RSG Contact Us</title>
<script>
// $(function () {
// $('form').on('submit', function (e) {
// $.ajax({
// type: 'post',
// url: 'contact.php',
// data: $('form').serialize(),
// success: function () {
// alert('Thank you! your form has been submitted');
// }
// });
// e.preventDefault();
// });
// });
</script>
</head>
<body>
<div id="contactuscall">
<?php
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$firstnameErr = $lastnameErr = $emailErr = $cellphoneErr = $genDerErr = $dognameErr = $BreedErr = $reasonErr = "";
$firstname = $lastname = $email = $cellphone = $genDer = $dogname = $Breed = $reasoN= $freecomments = "";
//if conditional statement stops PHP from looking for variable values until the submit button is hit
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// check if a first name was provided
if (empty($_POST["firstname"]))
{$firstnameErr = "A first name is required";}
else
{
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
{$firstnameErr = "Only letters and white space allowed";}
}
//check if a last name was provided
if (empty($_POST["lastname"]))
{$lastnameErr = "A last name is required";}
else
{
$lastname = test_input($_POST["lastname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname))
{
$lastnameErr = "Only letters and white space allowed";
}
}
// check if an email was provided
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["cellphone"]))
{$cellphoneErr = "Please provide a phone number";}
else {
$cellphone = test_input($_POST["cellphone"]);
// Regular Expression to allow only valid phone number formats, including numbers, spaces, dashes, extensions
if (!preg_match("/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/",$cellphone))
{$cellphoneErr = "Invalid format";}
}
if (empty($_POST["dogname"]))
{$dognameErr = "A doggy name is required";}
else {
$dogname = test_input($_POST["dogname"]);
// check if dogname only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$dogname))
{$dognameErr = "Only letters and white space allowed";}
}
if (empty($_POST["Breed"]))
{$BreedErr = "A breed name is required";}
else {
$Breed = test_input($_POST["Breed"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Breed))
{$BreedErr = "Only letters and white space allowed";}
}
if(empty($_POST['genDer']))
{$genDerErr= "You forgot to select a Gender!";}
else {
$genDer=($_POST['genDer']);
}
//make sure one of the services requested checkboxes are checked
$reasoN = $_POST['reasoN'];
if(empty($reasoN))
{
$reasonErr="You didn't select any services.";
}
else
{
$N = count($reasoN);
$reasonErr="You selected $N services(s): ";
}
// if comment section is not empty then run test_input function to purge possible malicious code
if (empty($_POST["freecomments"]))
{$freecomments = "";}
else
{$freecomments = test_input($_POST["freecomments"]);}
}
$host="fdb3.biz.nf"; //localhost
$dbuser="1546259_rsginfo"; //user
$dbpass="RSGnow12"; //pass
$dbname="1546259_rsginfo"; //db name
// Create connection
$conn=mysqli_connect($host,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//create query
$sql= "INSERT INTO customer (fname, lname, email, phone, comments)VALUES ('$firstname', '$lastname', '$email', '$cellphone', '$freecomments')";
$sql2= "INSERT INTO DogInfo (DogName, Breed, Lookingfor)VALUES ('$dogname', '$Breed', '$reasoN')";
// execute query
mysqli_query($conn,$sql);
mysqli_query($conn, $sql2);
// close connection
mysqli_close($conn)
?>
<form id="form1" name="form1" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<fieldset id="field1">
<legend id="legend1">Contact info:</legend>
<hr />
First name: <input type="text" id="firstname" name="firstname" size="30" class="textfield" value="<?php echo $firstname;?>">
<span class="error">* <?php echo $firstnameErr;?></span>
E-mail: <input type="text" size="30" name="email" class="textfield" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span><br />
Last name: <input type="text" id="lastname" name="lastname" size="30" class="textfield" value="<?php echo $lastname;?>">
<span class="error">* <?php echo $lastnameErr;?></span>
Cell: <input type="text" id="cellphone" name="cellphone" size="30" class="textfield" value="<?php echo $cellphone;?>">
<span class="error">* <?php echo $cellphoneErr;?></span><br />
</fieldset>
<fieldset id="field2">
<legend id="legend2">Doggie info:</legend>
<hr />
Name: <input type="text" id="dogname" name="dogname" size="20" class="textfield" value="<?php echo $dogname;?>"><span class="error">* <?php echo $dognameErr;?></span>
Breed: <input type="text" id="Breed" name="Breed" size="20" class="textfield" value="<?php echo $Breed;?>"><span class="error">* <?php echo $BreedErr;?></span>
<p>
Gender:<select name="genDer" class="textfield">
<option value="">--</option>
<option value="Intact Male" <?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Intact Male" ? "selected" : "" ?>>Intact Male</option>
<option value="Neutered Male"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Neutered Male" ? "selected" : "" ?>>Neutered Male</option>
<option value="Intact Female"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Intact Female" ? "selected" : "" ?>>Intact Female</option>
<option value="Neutered Female"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Neutered Female" ? "selected" : "" ?>>Neutered Female</option>
</select><span class="error">* <?php echo $genDerErr;?></span>
</p>
</fieldset>
<fieldset id="field3">
<legend id="legend3">Services Required:</legend>
<hr />
<input type="checkbox" name="reasoN[]" value="walkSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking for a Dog Walker!
<input type="checkbox" name="reasoN[]" value="RawSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking to purchase Raw Food!
<input type="checkbox" name="reasoN[]" value="groomSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking for a Dog Groomer!
<span class="error">* <?php echo $reasonErr;?></span>
<?php echo $reasonConfirm;?>
</fieldset>
<fieldset id="field4">
<legend id="legend4">Comments & Questions</legend>
<hr />
<textarea rows="7" cols="90" id="freecomments" name="freecomments"><?php echo $freecomments;?></textarea>
</fieldset>
<input id="submit" type="submit" name="submit" value="submit">
</form>
</div>
<?php
echo "<h2>Your Input:</h2>";
echo $firstname;
echo "<br>";
echo $lastname;
echo "<br>";
echo $email;
echo "<br>";
echo $cellphone;
echo "<br>";
echo $dogname;
echo "<br>";
echo $Breed;
echo "<br>";
echo $genDer;
echo "<br>";
echo $reasoN;
echo "<br>";
echo $freecomments;
?>
</body>
</html>
Your code actually tries to insert values in to the table whether or not the validation is successful. The easiest and the quickest solution for this is to use a boolean flag.
eg:
// ...
$formValid = true; // Define a boolean and set to true before validating
//if conditional statement stops PHP from looking for variable values until the submit button is hit
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// check if a first name was provided
if (empty($_POST["firstname"]))
{
$firstnameErr = "A first name is required";
} else {
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
{
$firstnameErr = "Only letters and white space allowed";
$formValid = false; // Invalid input - set the flag to false
}
}
}
// ....
// Eventually wrap the mysql logic inside a condition
if ($formValid)
{
// Create connection
$conn=mysqli_connect($host,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//create query
$sql= "INSERT INTO customer (fname, lname, email, phone, comments)VALUES ('$firstname', '$lastname', '$email', '$cellphone', '$freecomments')";
$sql2= "INSERT INTO DogInfo (DogName, Breed, Lookingfor)VALUES ('$dogname', '$Breed', '$reasoN')";
// execute query
mysqli_query($conn,$sql);
mysqli_query($conn, $sql2);
// close connection
mysqli_close($conn);
}
// ... rest of your code

Categories