Inserting Form Data into SQL table - php

I've been trying to figure this out for hours and it seems like there are multiple ways of doing it but for some reason I can't seem to get it to work correctly. For some reason my table is being updated and I am only seeing new rows with a new auto increment integer but the remaining columns are left blank. There is a bit more to that form but I left it off to keep this as short as possible. Thanks for the help!
File: dbh.inc.php
$dbServername = "localhost";
$dbUsername = "username";
$dbPassword = "password";
$dnName = "database_name";
$conn = mysqli_connect($dbServername, $dbUsername,
$dbPassword, $dnName);
if(!$conn)
// creation of the connection object failed
die("connection object not created: ".mysqli_error($conn));
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
File with form:
$name7 = $_POST['name7'];
$email7 = $_POST['email7'];
$phone7 = $_POST['phone7'];
$message7 = $_POST['message7'];
$sql = "INSERT INTO user_contacts (name7, email7, phone7, message7) VALUES ('".$_POST["name7"]."','".$_POST["email7"]."','".$_POST["phone7"]."','".$_POST["message7"]."')";
mysqli_query($conn, $sql);
?>
<div class="form-group">
<form action="dbh.inc.php" method="POST">
<input type="text" class="form-control" name="name7" id="name7" placeholder="<?php esc_html_e('Name:','listingpro'); ?>">
<span id="name7"></span>
</div>
<div class="form-group form-group-icon">
<i class="fa fa-envelope" aria-hidden="true"></i>
<input type="email" class="form-control" name="email7" id="email7" placeholder="<?php esc_html_e('Email:','listingpro'); ?>">
</div>
<div class="form-group">
<input type="text" class="form-control" name="phone7" id="phone7" placeholder="<?php esc_html_e('Phone','listingpro'); ?>">
<span id="phone7"></span>
</div>
<div class="form-group">
<textarea class="form-control" rows="5" name="message7" id="message7" placeholder="<?php esc_html_e('Message:','listingpro'); ?>"></textarea>
</div>

I have Just Edited your sql a little bit. Try It
$sql = "INSERT INTO user_contacts (name7, email7, phone7, message7) VALUES ('".
$name7. "','" . $email7 . "','". $phone7 ."','". $message ."')";

Related

Updating records in database using a pre populated form

Looks like I have 1 last issue that I can't solve due to the fact of being too unexperienced with this matter. This last issue that I can't get to work or basically I don't understand the order in how to do this.
Been able to do the following:
Form that writes records to database
Page that shows database records in a table
Added an edit button to the table that takes you to an edit.php page with a form that has all values pre filled.
What I'm trying to get to work now is to edit one of the inputs on the form so it get's updated in the database.
So far I have this on the edit.php page:
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, email, age FROM members WHERE id =" .$_GET['id'];
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$id = $row['id'];
$name = $row['name'];
$email = $row['email'];
$age = $row['age'];
?>
<form action=" <?=$_SERVER['PHP_SELF']?> " method="POST">
<div align="center">
<div class="container">
<div class="row">
<div class="col-25">
<label for="#"></label>
</div>
<div class="col-75">
<h2>ID: <?php echo $row['id']; ?></h2>
</div>
</div>
<br>
<div class="row">
<div class="col-25">
<label for="name">Name:</label>
</div>
<div class="col-75">
<input type="text" name="name" value="<?php echo $row['name']; ?>" id="my-input" class="input-res">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="email">Email:</label>
</div>
<div class="col-75">
<input type="text" name="email" value="<?php echo $row['email']; ?>" class="input-res">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="age">Age:</label>
</div>
<div class="col-75">
<input type="text" name="age" value="<?php echo $row['age']; ?>" class="input-res">
</div>
</div>
<div class="row"><br>
<input type="submit" name="submit" value="Save updates" class="button">
</div>
</div>
</div>
</form>
</body>
</html>
Have tried adding this code below the form:
<?php
if(isset($_POST['Submit'])){//if the submit button is clicked
$sql="UPDATE name, email, age SET name, email, age WHERE name = ".$name.", email = ".$email.", age = ".$age.";
$conn->query($sql) or die("Cannot update");//update or error
}
?>
But the the page doesn't work anymore, tried changing from single quotes to double qoutes etc. but no success and a few other solutions (that unfortunatelly didn't work).
Need $_POST to get posted value
Use prepare for security
note: die is a wrong idea here
Correct code will be:
<?php
if (isset($_POST['Submit'],$_POST['name'],$_POST['email'],$_POST['age'],$_GET['id'])) { //if the submit button is clicked
$stmt = $conn->prepare('UPDATE name, email, age SET name = ?, email = ?, age = ? WHERE id=?');
$stmt->bind_param('ssii', $_POST['name'], $_POST['email'], $_POST['age'], $_GET['id']);
$stmt->execute();
echo "Updated successfully"; // Updated Successfully
}

Have a Insert and a Edit button in the same form using PHP and SQL

I've been going at this for a couple of hours now (searching here and google) but nothing I find helped me to get this to work.
I'm trying to make one form and have a Insert INTO and UPDATE $table SET function in the same form, using buttons.
But whatever I try the Update doesn't copy the data from the form. INSERT INTO works. But when I try to edit the form, no data is copied.
HTML:
<form id="contact-form" method="post" action="cms_data.php" role="form">
<div class="col-sm-12">
<h2>id</h2>
<input name="id" type="text" placeholder="<?php echo $id;?>" value="1">
</div>
<div class="col-sm-12">
<h2>Omschrijving</h2>
<textarea name="omschrijving" type="text" style="height:220px;width:100%;resize:none;"><?php echo $omschrijving;?></textarea>
</div>
<div class="col-sm-12">
<h2>Datum</h2>
<input name="datum" type="text" value="<?php echo $datum;?>">
</div>
<div class="col-sm-12">
<h2>Tijd</h2>
<input name="tijd" type="text" value="<?php echo $tijd;?>">
</div>
<div class="col-sm-12">
<h2>Locatie</h2>
<input name="locatie" type="text" value="<?php echo $locatie;?>">
</div>
<div class="col-sm-12">
<h2>Dresscode</h2>
<input name="dresscode" type="text" value="<?php echo $dresscode;?>">
</div>
<div class="col-sm-12 text-right">
<input type="submit" class="btn btn-success btn-send" value="Versturen" id="sent" <?php // echo $_SESSION['disabled']; ?>>
Update
</div>
</form>
CMS_DATA.php
<?php session_start();?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//echo '<div style="width:100%;background:green;color:#FFF;font-size:2rem;text-align:center;">Connected to '. $dbname. '</div>';
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_POST['id'];
$omschrijving = $_POST["omschrijving"];
$datum = $_POST["datum"];
$item = $_POST["tijd"];
$locatie = $_POST["locatie"];
$dresscode = $_POST["dresscode"];
$quote = iconv("UTF-8", "WINDOWS-1252//TRANSLIT");
$date = date('Y-m-d');
date_default_timezone_set("Europe/Amsterdam");
$time = date("h:i:sa");
$sql = "INSERT INTO $table (ID, Omschrijving, Datum, Tijd, Locatie, Dresscode )
VALUES ('" .$id."','" .$omschrijving."','".$datum."',' ".$item."','".$locatie."','".$dresscode."')";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
UPDATE-CMS.php
<?php session_start();?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//echo '<div style="width:100%;background:green;color:#FFF;font-size:2rem;text-align:center;">Connected to '. $dbname. '</div>';
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_POST['id'];
$omschrijving = $_POST["omschrijving"];
$datum = $_POST["datum"];
$item = $_POST["tijd"];
$locatie = $_POST["locatie"];
$dresscode = $_POST["dresscode"];
$quote = iconv("UTF-8", "WINDOWS-1252//TRANSLIT");
$date = date('Y-m-d');
date_default_timezone_set("Europe/Amsterdam");
$time = date("h:i:sa");
$sql = "UPDATE $table SET
Omschrijving = '$omschrijving', Datum = '$datum', Tijd = '$item', Locatie = '$locatie', Dresscode = '$dresscode' WHERE ID = '1'";
if ($conn->query($sql) === TRUE) {
echo "Done";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Like I said, the INSERT INTO works fine. But no data (values) are copied when using the update. I just overrides ID 1 with empty rows... I hope someone can help me... thanks in advance.
You have defined action on your form action="cms_data.php", so your button that is responsible for submitting that form works correctly, but on the other hand you've defined another button (anchor tag), that only has href (hence points to another page), so if you click on it, you won't pass any arguments with it.
My suggestion here is, as I mentioned in comment below your question, to use two buttons, both with submit property, but then handle clicking on them via JavaScript.
When you capture submitment, you can dinamically change action on your form, so your data will be passed to desired script.
Handling multiple buttons in a form:
Process a Form Submit with Multiple Submit Buttons in Javascript
Manipulating form's action property:
How to use JavaScript to change the form action
Another suggestion would be that you use prepared statements in your query, so you wouldn't be vulnerable to SQL injections (from the comments section, I see you'll only be using this locally, but this is a good practice).
Using Mysqli prepared statements:
https://stackoverflow.com/a/24989090/5018750
Echo only prints value on the screen in your respective textbox and does not assign that value to your actual field.
Instead what you can do is start the session in the start of your contact form and store those fields in session variable.
When user selects UPDATE option he will get redirected to UPDATE-CMS.php page. In UPDATE-CMS.php you can retrieve your stored session variables and assign them to your actual variables. In this way you can carry forward your old as well as new values.
anchor just links the page it will not pass data
you are trying to have submit and update button in one form
solution:
in html5 button has formaction attribute .formaction specifies page data to be transferred .so that different button can have different action page
<form id="contact-form" method="post" action="cms_data.php" role="form">
<div class="col-sm-12">
<h2>id</h2>
<input name="id" type="text" placeholder="<?php echo $id;?>" value="1">
</div>
<div class="col-sm-12">
<h2>Omschrijving</h2>
<textarea name="omschrijving" type="text" style="height:220px;width:100%;resize:none;"><?php echo $omschrijving;?></textarea>
</div>
<div class="col-sm-12">
<h2>Datum</h2>
<input name="datum" type="text" value="<?php echo $datum;?>">
</div>
<div class="col-sm-12">
<h2>Tijd</h2>
<input name="tijd" type="text" value="<?php echo $tijd;?>">
</div>
<div class="col-sm-12">
<h2>Locatie</h2>
<input name="locatie" type="text" value="<?php echo $locatie;?>">
</div>
<div class="col-sm-12">
<h2>Dresscode</h2>
<input name="dresscode" type="text" value="<?php echo $dresscode;?>">
</div>
<div class="col-sm-12 text-right">
<buttin formaction="CMS-DATA.php" type="submit" class="btn btn-success btn-send" value="Versturen" id="sent" <?php // echo $_SESSION['disabled']; ?>>
<button formaction="UPDATE-CMS.php" >Update </button>
</div>
</form>

PHP SQL Form Insert Creation

I am trying to create a simple form that will insert the given data received by my HTML form, into my SQL table named 'Vendors', however I am struggling to work with its functionality.
There are 7 text fields that I am wanting to add to my Vendors table, and these are so named:
vendorName
addressL1 (Line 1)
addressL2
postcode
email
telephone
description
The HTML for this form can be found below:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form action="" method="post">
<ul class="form-style-1">
<li>
<label style="color:#4D4D4D;" >Vendor Name <span class="required">*
</span></label>
<center> <input type="text" name="vendorName" class="field-long"
required="required" placeholder="Vendor Name" /> </center>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Address <span class="required">*
</span></label>
<center> <input type="text" name="addressL1" required="required"
class="field-long" placeholder="Address Line 1" /> </center>
</br>
<center> <input type="text" name="addressL2" required="required"
class="field-long" placeholder="Address Line 2" /> </center>
</br>
<center> <input type="text" name="postcode" required="required"
class="field-short" placeholder="Postcode" /> </center>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Contact Details <span
class="required">*</span></label>
<center> <input type="text" name="email" required="required"
class="field-long" placeholder="Email Address" /> </center>
</br>
<center> <input type="text" name="telephone" required="required"
class="field-long" placeholder="Phone Number" /> </center>
</select>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Description </label>
<center> <textarea name="description" id="field5" class="field-long
field-textarea" placeholder="Description"></textarea> </center>
</li>
<li>
<center> <input type="submit" class="AddButton" value="POST"></input>
</center>
</li>
</ul>
</form>
</body>
</html>
And the PHP I have used is:
<?php
date_default_timezone_set('Europe/London');
$server = "";
$connectionInfo = array( "Database"=>"");
$conn = sqlsrv_connect($server,$connectionInfo);
if (!$conn)
{
die("Connection failed");
}
$_SERVER['REQUEST_METHOD'];
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$VendorName = $_POST['vendorName'];
$AddressLine1 = $_POST['addressL1'];
$AddressLine2 = $_POST['addressL2'];
$Postcode = $_POST['postcode'];
$VendorEmail = $_POST['email'];
$VendorNumber = $_POST['telephone'];
$VendorDes = $_POST['description'];
$time = time();
$timestamp = date("Y-m-d H:i:s", $time);
$describeQuery = ("INSERT INTO Vendors (VendorName, VendorAL1,
VendorAL2, VendorPost, VendorEmail, VendorNumber, VendorDes,
Added)
VALUES ('".$VendorName."', '".$AddressLine1."',
'".$AddressLine2."', '".$Postcode."',
'".$VendorEmail."', '".$VendorNumber."',
'".$VendorDes."', '".$timestamp."')");
$results = sqlsrv_query($conn, $describeQuery);
if(sqlsrv_query($conn, $describeQuery))
{
$alert = "Vendor Successfully Added";
echo "<script type='text/javascript'>alert('$alert');
</script>";
}
else
{
echo 'Information not inserted';
}
}
sqlsrv_close($conn);
?>
Each time I submit the form, it goes straight to the 'Information not inserted' ELSE statement and doesn't import the data into my database.
I have removed my server name and database name for precautionary reasons, however I can assure you they are correct as I have worked on a previous project and used the same method of connecting.
Any help on this would be greatly appreciated, and if there are any formatting mistakes, apologies in advance, I am not an avid user of stack overflow.
Use Mysqli Please, I have updated the script.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Vendors (VendorName, VendorAL1,
VendorAL2, VendorPost, VendorEmail, VendorNumber, VendorDes,
Added)
VALUES ($VendorName, $AddressLine1, $AddressLine2,$Postcode,$VendorEmail,$VendorNumber,$VendorDes,$timestamp)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>

Fatal error: Function name must be a string in line 12

Edited: This is the error I got.
$categoryName = $_POST['category_name'] ;
$categoryDesc = $_POST['category_desc'] ;
$sql = "INSERT INTO category (category_title, category_desc) VALUES ('$categoryName','$categoryDesc')";
if (mysqli_query($con,$sql))
{
echo 'Inserted successfully';
}
else
{
echo 'Inserted Failed';
}
mysqli_close($con);
?>
The error I got is Fatal error: Function name must be a string in line 12
line 12 : $categoryName = $_POST['category_name'] ;
[EDITED]
dbconnect.php (I am not sure that I am right or wrong because I am using virtual host, that's why my servername is my virtual host name)
<?php
$servername = "wp-one";
$username = "root";
$password = "";
$dbName = "personality_test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
html code
<div class="col-lg-6">
<form role="form" action="../controller/AddCategory&Question.php?create=true" method="post">
<div class="form-group">
<label>Category Name</label>
<input class="form-control" type="text" placeholder="CategoryName" name="category_name" />
</div>
<div class="form-group">
<label>Category Description</label>
<input class="form-control" type="text" placeholder="CategoryDesc" name="category_desc" />
</div>
<div class="form-group input_fields_wrap">
<button class="add_field_button btn btn-default" style="margin-bottom:10px;">Add New Question</button>
<div class="form-group">
<div class="row">
<div class="col-lg-2"><input type="text" placeholder="Number" class="form-control" name="criteria[]"></div>
<div class="col-lg-5"><input type="text" placeholder="Question" class="form-control" name="grade[]"></div>
</div>
</div>
</div>
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
Please help me, Thank You so much
$conn = new mysqli(...);
so you must use $conn instead of $con
if (mysqli_query($conn,$sql))
{
echo 'Inserted successfully';
}
else
{
echo 'Inserted Failed';
}
mysqli_close($conn);
whats your data type for category_title in database?
Your Error in connection
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
you use $conn and in insert file you use $can instead of $conn...

$_POST['var'] into MySQL DB?

I am using WAMP to try and learn a little PHP and SQL. I'm trying to take user input from a very basic table here:
<form action="input.php" method="post" class="registration_form"/>
<fieldset>
<div class="elements">
<label for="name">Username :</label>
<input type="text" id="name" name="name" size="25" />
</div>
<div class="elements">
<label for="e-mail">E-mail :</label>
<input type="text" id="e-mail" name="e-mail" size="25" />
</div>
<div class="elements">
<label for="Password">Password:</label>
<input type="password" id="Password" name="Password" size="25" />
</div>
<div class="submit">
<input type="hidden" name="formsubmitted" value="TRUE" />
<input type="submit" value="Register" />
</div>
</fieldset>
</form>
and I want to be able to take the input and post to a database. I've been trying to make this happen with this code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (name, email, password)
VALUES ($_POST[name], $_POST[e-mail], $_POST[password])";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;//
}
$conn->close();
var_dump('name', 'e-mail', 'password');
?>
When I try and insert the "" as in $_POST["name"] I get an error:
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\wamp\www\input.php on line 16
When I try to remove the "" I get this error:
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\wamp\www\input.php on line 16
I also tried to set the variables in the top of the code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$name=$_POST['name']
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (name, email, password)
VALUES ('name','email', 'password');
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;//
}
$conn->close();
var_dump('name', 'e-mail', 'password');
?>
This way I ended up with an error message saying:
( ! ) Parse error: syntax error, unexpected '$conn' (T_VARIABLE) in C:\wamp\www\input.php on line 9
I was able to echo the name in another script using the $_POST, I am not sure why it will not work with the SQL command. If anyone would help out, and/or give me some resources to learn/study from as well I would appreciate it!
You have a missing ';' after:
$name=$_POST['name']
Hi Please note some points
1) You will get warnings of undefined index because you are not checking about values posted or not. We Should use isset() before using values.
2) Second try to use lowercase whenever you are giving any name to any tag in php to be sure that no error exist due to typing in lowercase or uppercase.
3) Try to use underscore if your word is long so use e_mail;
So you can use this php code
<?php
if(isset($_POST['register'])){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_POST['name'];
$email = $_POST['e_mail'];
$password = $_POST['password'];
$sql = "INSERT INTO MyGuests(name, email, password) VALUES('$name','$email','$password')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;//
}
$conn->close();
}
?>
I have added name to your submit button also changed e-mail to e_mail and name="Password" to name="password"
<form action="input.php" method="post" class="registration_form"/>
<fieldset>
<div class="elements">
<label for="name">Username :</label>
<input type="text" id="name" name="name" size="25" />
</div>
<div class="elements">
<label for="e-mail">E-mail :</label>
<input type="text" id="e_mail" name="e_mail" size="25" />
</div>
<div class="elements">
<label for="Password">Password:</label>
<input type="password" id="Password" name="password" size="25" />
</div>
<div class="submit">
<input type="hidden" name="formsubmitted" value="TRUE" />
<input type="submit" value="Register" name="register" />
</div>
</fieldset>
</form>

Categories