input form data into database through php - php

I cannot figure out what is wrong with my code. The data is not getting stored in phpmyadmin. may be its a syntax error.I ll be glad if someone could find the problem with my code. Please help me out on this!
It is a simple form asking for the details of the person who needs blood. I need the details to be stored into the database named 'blood_share_system' and the table name 'acceptors'.
my html file:
<form action="needblood.inc.php"method="post">
<fieldset>
<legend>Personal Information</legend>
<label>FirstName</label><br>
<input type="text"name="first"required><br>
<label>LastName</label><br>
<input type="text"name="last"required><br>
<label>PatientFirstName</label><br>
<input type="text"name="pfirst" required><br>
<lable>PatientLastName</label><br>
<input type="text"name="plast"<br>
</legend>
</fieldset>
<fieldset>
<legend>Contact Information</legend>
<lable>Phone Number</label><br>
<input type="tel"placeholder="10-digit PhoneNumber"name="phno" required><br>
<lable>Email Address</label><br>
<input type="email" placeholder="Valid email address"name="email"><br>
</fieldset>
<fieldset>
<legend>Blood Group Information</legend>
<label>Blood Group</label><br>
<select name="bgroup">
<option value="1">O-positive</option>
<option value="2">O-negative</option>
<option value="3">A-positive</option>
<option value="4">A-negative</option>
<option value="5">B-positive</option>
<option value="6">B-negative</option>
<option value="7">AB-positive</option>
<option value="8">AB-negative</option>
</select><br>
<label>Quantity required(1Unit:350ml):</label><br>
<button class="nbtn"id="snbtn"onclick="nbuttonClick()">-</button>
<input type="number" readonly="true" id="inc" value="0"name="quantity"required>
<button class="pbtn"id="sbtn"onclick="buttonClick()">+</button>Unit</h4><br>
<input type="number" id="result">ml
</fieldset>
<fieldset>
<legend>Location Details</legend>
<label>Locality</lable><br>
<input type="text"name="loc"required><br>
<label>Pincode</label><br>
<input type="number"name="pincode"required>
</fieldset>
<input type="submit" name="submit"value="Submit">
</form>
my php file:
<?php
//first if
if(isset($_POST['submit'])){
$dbserverName = "localhost";
$dbuserName = "root";
$dbpassword = "";
$dbname = "blood_share_system";
$conn = mysqli_connect( $dbserverName , $dbuserName , $dbpassword , $dbname);
//2nd if
if(!$conn){
echo "connection was not established with server";
}//2nd if close
//3rd if
if(!mysqli_select_db($conn,'blood_share_system')){
echo "not connected to the database";
}//3rd if close
$first=mysqli_real_escape_string($conn,$_POST['first']);
$last=mysqli_real_escape_string($conn,$_POST['last']);
$pfirst=mysqli_real_escape_string($conn,$_POST['pfirst']);
$plast=mysqli_real_escape_string($conn,$_POST['plast']);
$phno=mysqli_real_escape_string($conn,$_POST['phno']);
$email=mysqli_real_escape_string($conn,$_POST['email']);
$bgroup=mysqli_real_escape_string($conn,$_POST['bgroup']);
$quantity=mysqli_real_escape_string($conn,$_POST['quantity']);
$locality=mysqli_real_escape_string($conn,$_POST['loc']);
$pincode=mysqli_real_escape_string($conn,$_POST['pincode']);
if (!preg_match("/^[a-zA-Z]*$/" , $first) || !preg_match("/^[a-zA-Z]*$/" , $last)||!preg_match("/^[a-zA-Z]*$/" , $pfirst)||!preg_match("/^[a-zA-Z]*$/" , $plast) ){
trigger_error('Enter valid names!',E_USER_ERROR);
} else {
if(!preg_match("/^[0-9]{10}$/", $phno)){
trigger_error('Enter 10 digit phone number!');
} else{
if (!filter_var( $email , FILTER_VALIDATE_EMAIL )){
trigger_error('Enter valid email address!',E_USER_ERROR);
} else{
if(!preg_match("/^[0-9]{6}$/", $pincode)){
trigger_error('Enter valid pincode!',E_USER_ERROR);
} else {
$sql="INSERT INTO acceptors('$first','$last','$pfirst','$plast','$phno','$email','$bgroup','$quantity','$locality','$pincode');";
if(!mysqli_query($conn, $sql)){
echo "Not inserted";
} else {
echo"Inserted";
}
}
}
}
}
}

One of the possible cause is use of insert into statement instead of insert into... values statement.
If you are using insert into statement, then you need to provide all the column values in the correct order of the columns.

Related

update page - update all records with the same data

I've small php project to list Covid-Test Labs, When you press the Update button for one of the records in the list of records, the data modification window opens, and when you enter it, the entries of other records are updated with the same information
How to solve this issue ?
<!-- Update Form -->
<form style = "font-size : 30px">
<input type="text" id="lab_name" class="fadeIn second" name="lab_name" placeholder="Laboratory Name" required>
<input type="text" id="test_price" class="fadeIn second" name="test_price" placeholder="Test Price" required>
<input type="text" id="lat" class="fadeIn second" name="lat" placeholder="Lat" required>
<input type="text" id="lon" class="fadeIn second" name="lon" placeholder="Lon" required>
<div class="dropdown">
<select name="lab_city" class="dropdown" required>
<option value="">--- Select City---</option>
<option value="Khartoum">Dubai</option>
<option value="Bahri">Bahri</option>
<option value="Omdurman">Paris</option>
</select>
<input type="file" name="image" id="image" required>
</div>
<input type="submit" id="submit" class="fadeIn fourth" value="Update">
</div>
</div>
</form>
<section>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "covidsd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$lab_id = $_GET['lab_id'];
$lab_name= mysqli_real_escape_string($link, $_REQUEST['lab_name']);
$lab_city = mysqli_real_escape_string($link, $_REQUEST['lab_city']);
$test_price= mysqli_real_escape_string($link, $_REQUEST['test_price']);
$lat= mysqli_real_escape_string($link, $_REQUEST['lat']);
$lon= mysqli_real_escape_string($link, $_REQUEST['lon']);
$image= mysqli_real_escape_string($link, $_REQUEST['image']);
//$ServerURL = "http://192.168.43.236/AndroidUploadImage/$ImagePath";
$sql = "UPDATE laboratories SET lab_name ='$lab_name',lab_city ='$lab_city', test_price= '$test_price', lat='$lat', lon= '$lon', image= '$image' ". "WHERE lab_id='$lab_id' ";
if(mysqli_query($link, $sql)){
$message = "Laboratory has been updated successfully";
echo "<script type='text/javascript'>alert('$message');</script>";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
I tried many solutions but not working
Each record in your table must have a unique id field. You will retrieve this field when loading your list. When modifying a record, you will send that id field again to PHP. Inside PHP you will use it in your SQL WHERE IdField=$ID.
You are using variable $lab_id In your PHP code $lab_id = $_GET['lab_id']; and this means that you have an input on your form with name lab_id. I can't see that input it in your HTML so you need to add it like that :
<form style = "font-size : 30px">
<input type="hidden" id="lab_id" name="lab_id" Value = "$lab_id">
<input type="text" id="lab_name" class="fadeIn second" name="lab_name" placeholder="Laboratory Name" required>
...............
...............
</form>
In your PHP code you must decide what kind of request you will accept either POST or GET. Now you are using a mix of $_GET and $_REQUEST. If you are modifying or inserting data, it will better to use $_POST. Getting variables is PHP code will looks like :
$lab_id = $_POST['lab_id'];
$lab_name= mysqli_real_escape_string($link, $_POST['lab_name']);
If you are using a framework which do the request, you can check it to make sure if it is sending lab_id, if it sends lab_id you will not need it inside form. You may also adjust the request type in your framework if you are using a one.

How do you trigger the next record in the PHP array via the HTML submit button?

Goal: I want to create an HTML form that displays pre-populated information from the 22 arrays from array_file.php.
First, I will go on index.php. On index.php, I will see a form with pre-populated data. I will not be able to edit the first and last name fields, but I will be able to edit the email field (if necessary).
Second, once everything looks okay, I will click the "Submit" button.
Third, if nothing is wrong (i.e., email field is populated), the "Submit" button should take me to the second record in the array.
Finally, once it has looped through all the arrays, it will provide a message, such as, "You're done!"
Current problem: My current index.php page shows all 22 pre-populated forms on one page. While I can edit and submit to the database using the individual "Submit" button, I'd rather be able to look at each pre-populated form one at a time.
Here is the code:
<?php
ob_start();
include 'array_file.php';
ob_end_clean();
?>
<?php
$i=1;
while ($i<=22){
?>
<form action="index.php" method="post">
<h2>Form</h2>
<label>First Name:</label>
<input class="input" name="first_name" type="text" value="<?php echo htmlentities($array[$i][1]) ?>" disabled><br>
<label>Last Name:</label>
<input class="input" name="last_name" type="text" value="<?php echo htmlentities($array[$i][2]) ?>" disabled><br>
<label>Email:</label>
<input class="input" name="email" type="text" value="<?php echo htmlentities($array[$i][3]) ?>"><br><br>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
<?php
$i=$i+1;
}
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = mysqli_real_escape_string($conn,$_POST['email']);
if($email !=''){
//Insert Query of SQL
mysqli_query(#conn,"INSERT into form(form_first_name, form_last_name, form_email) values ('$first_name', '$last_name', '$email')");
echo "<br/><br/><span>Data inserted successfully!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some required fields are blank!</p>";
}
}
$mysqli->close(); // Closing Connection with Server
?>
Let me know if you need me to provide any more information. Thank you in advance!
I hope this code is what you need.
<?php
ob_start();
include 'array_file.php';
ob_end_clean();
if(isset($_POST['submit']) and isset($_POST[email])){
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = mysqli_real_escape_string($conn,$_POST['email']);
if($email !=''){
//Insert Query of SQL
mysqli_query(#conn,"INSERT into form(form_first_name, form_last_name, form_email) values ('$first_name', '$last_name', '$email')");
echo "<br/><br/><span>Data inserted successfully!</span>";
}
}
/// find which form will be published
if( isset($_SESSION["form"]) and $_SESSION["form"]<22){
$form=$_SESSION["form"]+1;
$_SESSION["form"]=$form;
}else{
$form=1;
$_SESSION["form"]=$form;
}
// determine which is the next form number
if($form<22){ $nextForm=$form+1; }else{ $nextForm="??"; }
<!-- form area !-->
<form action="index.php?form=<?php echo $nextForm; ?>" method="post">
<h2>Form</h2>
<label>First Name:</label>
<input class="input" name="first_name" type="text" value="<?php echo htmlentities($array[$form][1]) ?>" disabled><br>
<label>Last Name:</label>
<input class="input" name="last_name" type="text" value="<?php echo htmlentities($array[$form][2]) ?>" disabled><br>
<label>Email:</label>
<input class="input" name="email" type="text" value="<?php echo htmlentities($array[$form][3]) ?>"><br><br>
<input class="submit" name="submit" type="submit" value="Submit">
</form>

How to insert steamid into database using the steam api

I am trying to log the users name, email, and region as well as their steamid via an html form.
The html form is here:
<form class="cptxt" action="/insert.php" method="post">
PUBG NAME: <input type="text" name="username" placeholder="Enter In Game
Name">
<br><br>
Email: <input type="text" name="email" placeholder="Enter Email"><br><br>
SteamID: <input type="text" name="sid" value="<?php echo
$steamprofile['steamid'] ?>" ><br><br>
SELECT REGION:
<select name="region">
<option value="NA">North America</option>
<option value="EU">Europe</option>
<option value="AS">Aisa</option>
<option value="OC">Oceianic</option>
</select> <br>
<br>
<input type="submit" value="Submit">
</form>
This is the insert.php file
<?php
require('connect.php');
include ('steamauth/userInfo.php');
if(!$con)
{
echo "NOT CONNECTED";
}
if(!mysqli_select_db($con,'pubgfinder'))
{
echo "db not selected";
}
$Name = $_POST['username'];
$Email = $_POST['email'];
$Sid = $_POST['sid']
$Region = $_POST['region'];
$sql = "INSERT INTO users (Name,Email,Region,Sid) VALUES
('$Name','$Email','$Region','$Sid')";
if(!mysqli_query($con,$sql))
{
echo "NOT INSERTED";
}
else
{
echo "INSERTED";
}
header("refresh:2; url=home.php");
?>
So far what I get is the form working, besides the steamid part of it. It writes the steamid into the form field as well, but doesn't send to the database.
Please help. Am I writing this wrong? What's the issue here?

HTML post to PHP

Trying to insert data into my table but I keep getting an undefined index because there are "no value set when I submit my form". The if (isset($_POST['submit'])) removes my error even when I run the .php alone but no data is inserted when I submit my form. Any help is appreciated. Thank you
My form.html
<form name="supportForm" class="form" action="database.php" method="POST" onsubmit="return validateForm()">
<label>Name:</label>
<input type="text" name="name"/>
<br/>
<label>Client ID:</label>
<input type="text" name="clientID"/>
<br/>
<label>E-mail address:</label>
<input type="email" name="email"/>
<br/>
<label>Phone number:</label>
<input type="tel" name="tel"/>
<br/>
<br/>
Support Type:<br>
<input type="radio" name="suppType" value="Question/Inquiry">Question/Inquiry<br>
<input type="radio" name="suppType" value="Software">Software Issue<br>
<input type="radio" name="suppType" value="Hardware">Hardware Issue<br>
<input type="radio" name="suppType" value="Connectivity">Connectivity<br>
</br>
Operating System:
<select id="select">
<option disabled selected value="">Choose a product</option>
<option value="w7" name="OS">Windows 7</option>
<option value="w8" name="OS">Windows 8/8.1</option>
<option value="w10" name="OS">Windows 10</option>
</select>
<br> </br>
Problem Description:
<br><textarea id="ta" rows="10" cols="80" name="pDesc"></textarea></br>
<input type="checkbox" name="terms" value="agree">
I agree to the terms and conditions.
<br> </br>
<input type="hidden" name="submitted" value="true">
<input type="submit" name="submit" onClick="validateSubmit()">
</form>
My PHP file
<?php
//Creates static credentials
define('DB_NAME', 'data');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
//Creates connection to the database
$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
//Checks for connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
//If there are no connection, error
if (!$con) {
die ('Could not connect' . mysqli_error());
}
//Select the 'data' database
$con->select_db(DB_NAME);
//Checks if database 'data' has been selected
if (mysqli_select_db($con, DB_NAME)) {
echo "Database exists <br>";
} else {
echo "Database does not exist";
}
//Successful connection message
echo "Connected successfully <br>";
if (isset($_POST['submit'])) {
//Retrieving values from support form
$name = $_POST['name'];
$clientID = $_POST['clientID'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$suppType = $_POST['suppType'];
$OS = $_POST['OS'];
$pDesc = $_POST['pDesc'];
//Inserting values into a table
$sql = "INSERT INTO info (fullname, clientID, email, tel,
suppType, OS, pDesc)
VALUES ($name, $clientID, $email, $tel,
$suppType, $OS, $pDesc)";
if (!mysqli_query($con, $sql)) {
echo "No data";
} else {
echo "Data recorded successfully";
}
}
//Closes connection
mysqli_close($con);
You must write name="OS" in <select> not in <option>
<select id="select" name="OS">
<option disabled selected value="">Choose a product</option>
<option value="w7">Windows 7</option>
<option value="w8">Windows 8/8.1</option>
<option value="w10">Windows 10</option>
</select>
And Sql must be like this you need apostrophes ('') around variables
$sql = "INSERT INTO `info` (fullname, clientID, email, tel, suppType, OS, pDesc)
VALUES ('$name', '$clientID', '$email', '$tel', '$suppType', '$OS', '$pDesc')";
You not showing us the validateForm() function, therefore we won't really know whats happening there, nonetheless I have edited your form and did a validation using php,
what you need to do first is to check if all values are set before jumping to insert into db, and make sure email is a proper email, also the select option the name attribute needs to be on the select tag not on the option tag, the option must only have values.
Then Validate,Filter and sanitize user input before storing to the
database. Treat every userinput on your form as if its from a very dangerous hacker.
There's something called prepared statements, in mysqli and PDO you should try to learn that and use it :) you will enjoy it, I will leave it to you to research as to why you need to use prepared statements.
This is how your code should look
<form name="supportForm" class="form" action="database.php" method="POST">
<label>Name:</label>
<input type="text" name="name"/>
<br/>
<label>Client ID:</label>
<input type="text" name="clientID"/>
<br/>
<label>E-mail address:</label>
<input type="email" name="email"/>
<br/>
<label>Phone number:</label>
<input type="tel" name="tel"/>
<br/>
<br/>
Support Type:<br>
<input type="radio" name="suppType" value="Question/Inquiry">Question/Inquiry<br>
<input type="radio" name="suppType" value="Software">Software Issue<br>
<input type="radio" name="suppType" value="Hardware">Hardware Issue<br>
<input type="radio" name="suppType" value="Connectivity">Connectivity<br>
</br>
Operating System:
<select id="select" name="OS">
<option value="0">Choose a product</option>
<option value="w7">Windows 7</option>
<option value="w8">Windows 8/8.1</option>
<option value="w10">Windows 10</option>
</select>
<br> </br>
Problem Description:
<br>
<textarea id="ta" rows="10" cols="80" name="pDesc"></textarea>
</br>
<input type="checkbox" name="terms" value="agree">
I agree to the terms and conditions.
<br> </br>
<input type="hidden" name="submitted" value="true">
<input type="submit" name="submit">
</form>
Then database.php
<?php
//Creates static credentials
define('DB_NAME', 'data');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$errors = ""; //checking for errors
//Creates connection to the database
$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
//Checks for connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
//If there are no connection, error
if (!$con) {
die('Could not connect' . mysqli_error());
}
//Select the 'data' database
$con->select_db(DB_NAME);
//Checks if database 'data' has been selected
if (mysqli_select_db($con, DB_NAME)) {
echo "Database exists <br>";
} else {
echo "Database does not exist";
}
//Successful connection message
echo "Connected successfully <br>";
if (isset($_POST['submit'])) {
//check values are set
if (empty($_POST['name'])) {
echo "enter name";
$errors++;
} else {
$name = userIput($_POST['name']);
}
if (empty($_POST['clientID'])) {
echo "enter id";
$errors++;
} else {
$clientID = userIput($_POST['clientID']);
}
if (empty($_POST['email'])) {
echo "enter email";
$errors++;
} else {
$email = userIput($_POST['email']);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) { //validate email,
echo "enter valid email";
$errors++;
}
}
if (empty($_POST['tel'])) {
echo "enter tel";
$errors++;
} else {
$tel = userIput($_POST['tel']);
}
if (!isset($_POST['suppType'])) {
echo "select one option";
$errors++;
} else {
$suppType = userIput($_POST['suppType']);
}
if (isset($_REQUEST['OS']) && $_REQUEST['OS'] === "0") {
echo "please select product";
$errors++;
} else {
$OS = userIput($_POST['OS']);
}
if (empty($_POST['pDesc'])) {
echo "enter Description";
$errors++;
} else {
$pDesc = userIput($_POST['pDesc']);
}
if ($errors <= 0) { // No errors
//prepare and insert query
$sql = $con->prepare("INSERT INTO info (fullname, clientID, email, tel,suppType, OS, pDesc) VALUES (?, ?, ?, ?, ?, ?, ?)");
$sql->bind_param("sssssss", $name, $clientID, $email, $tel, $suppType, $OS, $pDesc);
if ($sql->execute()) {
echo "records inserted successfully";
} else {
echo "Could not insert " . mysqli_error();
}
$sql->close();
$con->close();
}
}
function userIput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Hope this will help a little, and you will learn a thing or two, and I'm always available for suggessions, just incase I missed something. Thanks

Joining two strings to create one variable in php

Ok so I have a registration form for users to register and it works fine in that when it submits it enters into my database. I want to add a feature that only users with a certain domain address can register and after looking this up the simplest way I can see to do it is to use a drop down menu with a list of the available domains accepted. My issue is that when I try and run the concatenation function to join them upon entry they are not being joined and added to the database correctly below is my HTML form and my php code.
<form name='registration' method="post" action="registerAdmin.php">
<label for="adminName"> Name: </label>
<input name="adminName" id="a" size="27" required/>
<br/>
<label for="adminEmail"> Email Address: </label>
<input type="text" name="adminEmail" id="a" size="15" required/> <select style="height:27px;width:5;" name="adminDomain"><option value="#ucc.ie">#ucc.ie</option></select>
<br/>
<label for="adminUsername"> Username: </label>
<input name="adminUsername" id="b" size="27" required/>
<br/>
<label for="password"> Password: </label>
<input type="password" name="adminPassword" id="b" size="27" required/>
<br/>
<br/>
<input id="boo" type="submit" name="button" value="Register" class="btn btn-danger btn-lg"/>
</form>
And my PHP code:
$servername = "localhost";
$username = "********";
$password = "********";
$dbname = "********";
// FORM HANDLING
$aName = $_POST["adminName"];
$aEmail = $_POST["'adminEmail"];
$aUsername = $_POST["adminUsername"];
$aPassword = $_POST["adminPassword"];
$aEmail .= $_POST["adminDomain"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO administrators (`adminName`, `adminEmail`, `adminUsername`, `adminPassword`)
VALUES ('".$aName."','".$aEmail."','".$aUsername."','".$aPassword."')";
if ($conn->query($sql) === FALSE) {
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
} else {
echo "Account has successfully been created, please click the link below to return to the login screen!";
}
$conn->close();
?>
Everything bar the email address gets entered into the database correctly.
There is an extra "'" in the below statement:
$aEmail = $_POST["'adminEmail"]; it has to be `$aEmail = $_POST["adminEmail"];`
This should sort out the issue.

Categories