Trying to post only one single column into database - php

Here is my code that inserts data into a database table, but I want grab data and display it inside those div below:
<?php
// only proccss the form if $_POST isn't empty
if ( ! empty( $_POST ) ) {
// connect to MySQL
$mysqli = new mysqli( 'localhost', 'root', '', 'mydb' );
// Check our connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
// insert our data
$sql = "INSERT INTO table1 ( name, email ) VALUES ('{$mysqli->real_escape_string($_POST['name'])}', '{$mysqli->real_escape_string($_POST['email'])}' )";
$insert = $mysqli->query($sql);
// print response from MySQL
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_id}";
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
// close our connection
$mysqli->close();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<input name="name" type="text">
<input name="email" type="email">
<input type="submit" value="Add">
</form>
Display each name and email here like:
<div class="name">Get Name Here from Database</div><div class="email">Get Email Here from Database</div>
The code above works on posting but I want to make it like, whenever I go to same page it must display that data rom database below the form.

Try to use binds variables and prepared statements:
<?php
$mysqli = new mysqli("localhost", "user", "pass", "db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (isset($_POST['scriptname'])) {
$scriptname = $_POST['scriptname'];
$stmt = $mysqli->prepare("INSERT INTO appslist(listall) VALUES (?)");
$stmt->bind_param('s', $scriptname);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Script Name: <input type="text" name="scriptname">
<input type="submit">
</form>
Ouput:
1 Row inserted.
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Related

Downloads PHP instead of Running

I am trying to make a form that submits data to my database on mySQL workbench. When ever I click submit it ends up downloading the php file instead of running. All files are in the same folder.
inventorylog.html
<form action="insert.php" method="post">
<input required type="text" name="sku_input" placeholder="Sku #" />
<br>
<input value="Add Sku" type="submit" name="submit" />
</form>
connect.php
<?php
$host="localhost";
$port=3306;
$socket="/tmp/mysql.sock";
$user="root";
$password="";
$dbname="Logs";
$con = mysqli_connect($host, $user, $password, $dbname, $port, $socket)
or die ('Could not connect to the database server' . mysqli_connect_error());
//$con->close();
?>
insert.php
<?php
/*Needs the connection object created in the connect.php file to work*/
header("LOCATION:inventorylog.html");
require('connect.php');
/*require('inventorylog.html');*/
/*Data from the html form is on the right. The objects that will be composed of that data is on the left.*/
if(isset($_POST['submit'])) {
$skunum = mysqli_real_escape_string($con, $_POST['sku_input']);
echo 'sku_input';
$sql = "INSERT INTO skulist (sku_input)
VALUES ('$skunum')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
}
?>

how can I stop my php form resubmitting input after page refresh

<?php
$connection = mysqli_connect("host", "username", "password")
or die("Couldn't connect to the server"); //no issue
$db = mysqli_select_db($connection, "dbname")
or die("Couldn't select database"); //no issue
$sql = "INSERT INTO vendor-tbl(company_name, industry, details, website, data_type, start_date) VALUES ('".$_POST['company_name']."','".$_POST['industry']."','".$_POST['details']."','".$_POST['website']."','".$_POST['data_type']."','".$_POST['start_date']."')";
// mysqli_query(($connection,$sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close(); //closes the connection
?>
<form autocomplete="on" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" role="form">
<label id="company_name">Company Name:</label><br/>
<input type="text" name="company_name" id="company_name" autocomplete='organization'><br/>
<label id="industry">Industry:</label><br/>
<input type="text" name="industry" id="industry" autocomplete='industry'><br/>
<label id="details">Details:</label><br/>
<input type="text" name="details" id="details" autocomplete='details'><br/>
<label id="website">Website:</label><br/>
<input type="text" name="website" id="website" autocomplete='website'><br/>
<label id="data_type">Data Type:</label><br/>
<input type="text" name="data_type" id="data_type" autocomplete='datatype'><br/>
<label id="start_date">Start Date:</label><br/>
<input type="text" name="start_date" id="start_date" autocomplete='startdate'><br/>
<button id="submitButton" value="submit" name="submit">Submit</button><br/>
</form>
When I refresh my form after just submitting data, it seems to add that data into phpmyadmin twice, and if I reload the form another time(blank form) it adds the data a third time etc. Is there any way of preventing this without using session variables?
I'm very inexperienced with php but I have tried using session variables but I didn't seem to get it working.
What you want to do is a "post/redirect/get", for which you use an 303. This way you do a post, and then are 'forced' to do a get. When you f5, you reload that get and so not your post..
see:
https://en.wikipedia.org/wiki/Post/Redirect/Get
https://en.wikipedia.org/wiki/HTTP_303
Use isset() to check if the button was entered
if (isset($_POST['submit'])) {
$connection = mysqli_connect("host", "username", "password")
or die("Couldn't connect to the server"); //no issue
$db = mysqli_select_db($connection, "dbname")
or die("Couldn't select database"); //no issue
$sql = "INSERT INTO vendor-tbl(company_name, industry, details, website, data_type,
start_date) VALUES ('".$_POST['company_name']."','".$_POST['industry']."','".$_POST['details']."','".$_POST['website']."','".$_POST['data_type']."','".$_POST['start_date']."')";
// mysqli_query(($connection,$sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Solution:
<?php
if($_POST){
$connection = mysqli_connect("host", "username", "password")
or die("Couldn't connect to the server"); //no issue
$db = mysqli_select_db($connection, "dbname")
or die("Couldn't select database"); //no issue
$sql = "INSERT INTO vendor-tbl(company_name, industry, details, website, data_type, start_date) VALUES ('".$_POST['company_name']."','".$_POST['industry']."','".$_POST['details']."','".$_POST['website']."','".$_POST['data_type']."','".$_POST['start_date']."')";
// mysqli_query(($connection,$sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close(); //closes the connection
Header("Location: " . $_SERVER['REQUEST_URI']);
}
?>

The PHP linked to this form isn't submitting entries to my database

I have a form on a website I'm working on which needs to submit information to a MySQL database. I'm primarily a web designer, and PHP is somewhat new to me. I've written this PHP code as the action for my HTML form, which is below:
<?php
//only process if $_POST isn't empty
if ( ! empty( $_POST ) ){
//connect to mysql
$mysqli = new mysqli( 'localhost', 'user', 'pass', 'dbname' );
//check connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
//insert data
$sql = ("
INSERT INTO `table` (`ID`, `u_fname`, `u_lname`, `u_email`)
VALUES (NULL, '{$mysqli->real_escape_string($_POST['u_fname'])}', '{$mysqli->real_escape_string($_POST['u_lname'])}', {$mysqli->real_escape_string($_POST['u_email'])}')");
$insert = $mysqli->query($sql);
//print response from sql
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_id}";
}
else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
//close connection
$mysqli->close();
}
?>
The relevant HTML form is here:
<div class="form-container">
<form action="signupform.php" method="post" class="isubmit" name="signup" onsubmit="swal({
type: 'success',
title: 'Thanks!',
showConfirmButton: false,
timer: 1500
})">
<input required type="text" name="u_fname" class="first-name" placeholder="First Name">
<input required type="text" name="u_lname" class="last-name" placeholder="Last Name">
<input required type="text" name="u_email" class="email" placeholder="Email">
<button class="isubmit submit-text" type="submit">submit</button>
</form>
</div>
The HTML and PHP files are separate but in the same directory. I'm aware the PHP needs to be made more secure to avoid injection, but that is not my issue. The issue is that when the submit button is pressed, the PHP does not send the entries to my database. The database remains unchanged, and what I need is for the information from the form fields to populate the database table when the user hits the submit button on the HTML form. Any help with my code or suggestions of a better method would be greatly appreciated.
Remove the mysqli_real_escape_string from your string in your query and set a variable to equal your post value. Your 'id' also needs to be removed from the insert as the ID in your database should be an auto increment. Added in an error validation and prepared statement to help prevent sql injection.
//insert data
<?php
if(!empty($_POST)) {
if(isset($_POST['submit'])){
//connect to mysql
$mysqli = mysqli_connect( 'localhost', 'user', 'pass', 'dbname' );
//check connection
if (!$mysqli) {
die( 'Connect Error: ' . mysqli_error());
}
$u_fname = mysqli_real_escape_string($mysqli, $_POST['u_fname']);
$u_lname = mysqli_real_escape_string($mysqli, $_POST['u_lname']);
$u_email = mysqli_real_escape_string($mysqli, $_POST['u_email']);
//VALIDATION ARRAY
$error = [
"u_fname"=> '',
"u_lname"=> '',
"u_email"=> ''
];
if($u_fname == '') {
$error['u_fname'] = "Please Enter Your First Name";
}
if($u_lname == '') {
$error['u_fname'] = "Please Enter Your Last Name";
}
if($u_email == '') {
$error['u_fname'] = "Please Enter Your Email";
}
else {
//IF NO ERRORS INSERT DATA
$stmt = mysqli_prepare($mysqli, "INSERT INTO `table` (`u_fname`, `u_lname`, `u_email`) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sss', $u_fname, $u_lname, $u_email);
mysqli_stmt_execute($stmt);
//print response from sql
if ($stmt ) {
echo "Success!";
}
else {
die("Error" . mysqli_error());
}
//close connection
mysqli_close($mysqli);
}
}
}
?>
And for the Form
<div class="form-container">
<form action="signupform.php" method="post" class="isubmit" name="signup">
<input required type="text" name="u_fname" class="first-name" placeholder="First Name">
<span><?php echo isset($error['u_fname']) ? $error['u_fname'] : ''?></span>
<input required type="text" name="u_lname" class="last-name" placeholder="Last Name">
<span><?php echo isset($error['u_lname']) ? $error['u_lname'] : ''?></span>
<input required type="text" name="u_email" class="email" placeholder="Email">
<span><?php echo isset($error['u_email']) ? $error['u_email'] : ''?></span>
<button class="isubmit submit-text" type="submit" name="submit">submit</button>
</form>
</div>

Get and insert Data into MySQL database using PHP with xampp on localhost

I have managed to connect to database and I manage to insert using following code.
<?php
$username = 'root';
$password = '';
$db = 'demo';
$conn = new mysqli ('localhost',$username, $password, $db) or die("unable to connect");
$sql="insert into persons (first_name,last_name,email_address) values ('sara','smith','email#email.com')";
$query=mysqli_query($conn,$sql);
if($query)
echo 'data inserted';
?>
But the problem is that when I try to enter data using HTML form, it didn't work for me. I have tried to follow different tutorials and different answers here on stackoverflow. Can anyone please tell me the easiest way of inserting and getting data from MySQL using PHP ?
If there is any easy tutorial or blog from where i can learn and understand all this, I would love to watch or read.
I manage to do it in following way.
Create a file name index.php with following code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="firstname" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
Then create another file name as insert.php
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);
// attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
//procedural style
$mysqli = mysqli_connect('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//inserting a record
$product_code = '"'.$mysqli->real_escape_string('P1234').'"';
$product_name = '"'.$mysqli->real_escape_string('42 inch TV').'"';
$product_price = '"'.$mysqli->real_escape_string('600').'"';
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO products (product_code, product_name, price) VALUES($product_code, $product_name, $product_price)");
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
A quick and untested example of using an HTML form with the POST method to insert data entered by a user into the db.
<?php
$result = false;
$dbhost = 'localhost';
$username = 'root';
$password = '';
$db = 'demo';
if( $_SERVER['REQUEST_METHOD']=='POST' ){
$conn = new mysqli ( $dbhost,$username, $password, $db );
if( $conn ){
$sql='insert into `persons` ( `first_name`,`last_name`,`email_address` ) values (?,?,?);';
$stmt=$conn->prepare( $sql );
$stmt->bind_param('sss', $_POST['firstname'], $_POST['lastname'], $_POST['email'] );
$result = $stmt->execute();
}
$conn->close();
}
?>
<!doctype html>
<html>
<head>
<title>Simple Form submission example</title>
</head>
<body>
<form method='post'>
<input type='text' name='firstname' />
<input type='text' name='lastname' />
<input type='text' name='email' />
<input type='submit' value='Submit' />
<?php
echo $result ? '<div>The database was updated</div>' : '';
?>
</form>
</body>
</html>
Try tutsplus or lynda, Provide you with the best tuto !

Sending Variables to MySQLi

i have been staring at this page for half an hour trying to figure out where i am going wrong. The first two variables are found and inserted into database, however the last two, 'email' and 'password' are not found, not inserted into database but still however pass the if statement. Any help will be much appreciated.
Form.php
<form name="signup" method="POST" action="signup.php">
<label for="signupFirstName">First Name</label>
<input type="text" id="signupFirstName" name="signupFirstName" />
<label for="signupLastName">Last Name</label>
<input type="text" id="signupLastName" name="signupLastName"/>
<label for="signupEmail">Email</label>
<input type="text" id="signupEmail" name="signupEmail" />
<label for="signupConfirmEmail">Confirm Email</label>
<input type="text" id="signupConfirmEmail" name="signupConfirmEmail"/>
<label for="signupPassword">Password</label>
<input type="text" id="signupPassword" name="signupPassword"/>
<label for="signupConfirmPassword">Confirm Password</label>
<input type="text" id="signupConfirmPassword" name="signupConfirmPassword"/>
<button name="submit" type="submit" >Submit Form</button>
</form>
signup.php
<?php
if (isset($_POST['signupFirstName']) || isset($_POST['signupLastName']) || isset($_POST['signupEmail']) || isset($_POST['signupPassword']) ) {
echo $_POST['signupEmail'];
$mysqli = new mysqli('localhost', 'user1', 'password', 'db2');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO members (First_Name, Last_Name, Email, Password) VALUES (?,?,?,?)");
$stmt->bind_param('ssss',$sample,$lastName,$email,$password);
// escape the POST data for added protection
$sample = isset($_POST['signupFirstName'])
? $mysqli->real_escape_string($_POST['signupFirstName'])
: '';
$lastName = isset($_POST['signupLastName'])
? $mysqli->real_escape_string($_POST['signupLastName'])
: '';
$email = isset($_POST['signupEmail'])
? $mysqli->real_escape_string($_POST['signupEmail'])
: '';
$password = isset($_POST['signupPassword'])
? $mysqli->real_escape_string($_POST['signupPassword'])
: '';
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
}
else{
echo "broken";
}
?>
You seem to be binding the params to your query before you actually set the variables. Move the bind_param() call above the execute() call.
You can also refactor your code to take out a lot of the junk. Example below:
<?php
function arr_get($array, $key) {
if (isset($array[$key])) {
return $array[$key];
}
return '';
}
if (isset($_POST['signupFirstName']) || isset($_POST['signupLastName']) || isset($_POST['signupEmail']) || isset($_POST['signupPassword']) ) {
echo $_POST['signupEmail'];
$mysqli = new mysqli('localhost', 'user1', 'password', 'db2');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO members (First_Name, Last_Name, Email, Password) VALUES (?,?,?,?)");
$stmt->bind_param('ssss', arr_get($_POST, 'signupFirstName'), arr_get($_POST, 'signupLastName'), arr_get($_POST, 'signupEmail'), arr_get($_POST, 'signupPassword'));
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
}
else {
echo "broken";
}
?>

Categories