I'm very new to php and I really want to learn it. I'm learning from w3school, but I can't manage to do this (saving to database)... I also tried specifying the values in the .php and managed not to get error but it did not save in the database. Please tell me what is wrong in this.
<form action="submit.php" method="POST">
<p>Name:<input type="text" name="name"/></p>
<p>Email:<input type="text" name="email"/></p>
<p>Message:<textarea rows="3" cols="1" name="message"></textarea></p>
Submit
</form>
PHP File
<?php
$con = mysqli_connect("localhost","root","","kellywood");
if (mysqli_connect_errno()) {
echo "Failed to connect to Database";
} else {
echo "Connected";
}
$sql = "INSERT INTO kellywood (messages.name, messages.email, messages.message) VALUES ('$_POST[name]','$_POST[email]','$_POST[message]')");
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
No error, and I specified the values but it did not save in the database.
<?php
$con = mysqli_connect("localhost","root","","kellywood");
if (mysqli_connect_errno()) {
echo "Failed to connect to Database";
} else {
echo "Connected";
}
mysqli_query($con,"INSERT INTO kellywood(messages.name, messages.email, messages.message) VALUES ('Peter', 'Griffin',35)");
mysqli_close($con);
?>
Sorry for the noob question but i'm very new in php... Please help
There are a few things that are incorrect.
First:
Submit
which should be a button and not a link:
<input type="submit" name="submit" value="Submit">
And based on a comment that was made: "database is kellywood, messages is the table."
This:
mysqli_query($con,"INSERT INTO kellywood(messages.name, messages.email, messages.message)
VALUES ('Peter', 'Griffin',35)");
Should be:
mysqli_query($con,"INSERT INTO messages (name, email, message)
VALUES ('Peter', 'Griffin',35)");
However and based on your input variables, it should resemble more like this:
mysqli_query($con,"INSERT INTO messages (name, email, message)
VALUES ('" . $name . "', '" . $email . "', '" . $message . "')");
While assigning your input variables such as:
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
Rewrite:
<?php
$con = mysqli_connect("localhost","root","","kellywood");
if (mysqli_connect_errno()) {
echo "Failed to connect to Database";
} else {
echo "Connected";
}
$name = $con->real_escape_string($_POST['name']);
$email = $con->real_escape_string($_POST['email']);
$message = $con->real_escape_string($_POST['message']);
mysqli_query($con,"INSERT INTO messages (name, email, message)
VALUES ('" . $name . "', '" . $email . "', '" . $message . "')");
mysqli_close($con);
?>
Or you can use:
<?php
$con = mysqli_connect("localhost","root","","kellywood");
if (mysqli_connect_errno()) {
echo "Failed to connect to Database";
} else {
echo "Connected";
}
$name = $con->real_escape_string($_POST['name']);
$email = $con->real_escape_string($_POST['email']);
$message = $con->real_escape_string($_POST['message']);
$sql = "INSERT INTO messages (name, email, message)
VALUES ('" . $name . "', '" . $email . "', '" . $message . "')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
else {
echo "SUCCESS!";
}
mysqli_close($con);
?>
HTML form
<form action="submit.php" method="POST">
<p>Name:<input type="text" name="name"/></p>
<p>Email:<input type="text" name="email"/></p>
<p>Message:<textarea rows="3" cols="20" name="message"></textarea></p>
<input type="submit" name="submit" value="Submit">
</form>
Both of the above worked on my server, using VARCHAR(255) for all 3 columns.
Columns: name - email - message
Try using a button type="submit", instead of the href tag.
Related
I have a form that I can post. I also have a sql database that it has a successful connection with. However, when I close the page out, the user input disappears. How can I make the user input part of the page content,almost like a guestbook kind of idea?
<p onclick="myFunction()">Click here to share your personal testimony</p>
<div id="formwindow">
<form action="http://needjesuskneadjesus.org/perstest.php" method="post">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr; ?></span>
<br>
Email: <input type="text" name="email">
<span class="error">* <?php echo $emailErr; ?></span>
<br>
Personal Testimony:<br> <textarea name="personalTestimony" rows="10" cols="50"></textarea><br>
<input type="Submit">
</form>
</div>
<script>
function myFunction() {
document.getElementById("formwindow").style.display = "block";
}
</script>
</br>
<?php
echo "Name: " . $_POST['name'];
?>
</br>
<?php
echo "Email: " . $_POST['email'];
?>
</br>
<?php
echo "Personal Testimony: " . $_POST['personalTestimony'];
?>
</br>
/* Attempt MySQL server connection.
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$name = mysqli_real_escape_string($link, $_REQUEST['name']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$personalTestimony = mysqli_real_escape_string($link,
$_REQUEST['personalTestimony']);
// attempt insert query execution
$sql = "INSERT INTO personalTestimony (name, email, testimony) VALUES
('$name', '$email', '$personalTestimony')";
if(mysqli_query($link, $sql)){
echo "Thanks for sharing your personal testimony.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
*/
?>
You can use PHP Sessions to store the users review, this will display the old one
<?php
session_start();
$name;
$email;
$personalTestimony;
if($link === false){
die('ERROR: Could not connect.' . mysqli_connect_error());
}
if (!isset($_POST['name']) && !isset($_POST['email']) && !isset($_POST['personalTestimony'])) {
$name = $_POST['name']);
$email = $_POST['email'];
$personalTestimony = $_POST['personalTestimony']);
// attempt insert query execution
$sql = mysqli_prepare($link, "INSERT INTO personalTestimony (name, email, testimony) VALUES ('$name', '$email', '$personalTestimony'))";
if(mysqli_query($link, $sql)){
echo 'Thanks for sharing your personal testimony.';
} else{
echo 'ERROR: Could not able to execute $sql. ' . mysqli_error($link);
}
} elseif (!empty($_SESSION['name']) || !empty($_SESSION['email']) || !empty($_SESSION['testimony'])) {
$_SESSION['name'] = $name;
$_SESSION['email'] = $email;
$_SESSION['testimony'] = $personalTestimony;
}
}
// close connection
mysqli_close($link);
?>
I replaced
mysqli_real_escape_string to mysqli_prepare since it's less characters and provides more safety. You can read more about it here.
This will only work until ether the session expires (You can configure this here) or the client clears their cookies.
I am trying to set up a form for a user to enter information and then for that information to be inserted into a SQL table. I am not getting any error messages but the table is not updating in my database.
My form page is this:
<!DOCTYPE html>
<html>
<head>
<title>Input 2</title>
</head>
<body>
<h1>Add a user</h1>
<form action="input-followup2.php" method="post">
First Name:
<br/>
<input type="text" name="firstName">
<br/>
<br>
Last Name:
<br/>
<input type="text" name="lastName">
<br/>
<br>
Email Address:
<br/>
<input type="text" name="emailAddress">
<br/>
<br>
Monthy Food Budget:
<br/>
<input type="number" step="0.01" name="foodBudget">
<br/>
<br>
Monthly Utility Budget:
<br/>
<input type="number" step="0.01" name="utilityBudget">
<br/>
<br>
Monthly Entertainment Budget:
<br/>
<input type="number" step="0.01" name="entertainmentBudget">
<br/>
<br>
<input name="Add User" type="submit" value="Submit">
</form>
</body>
The action for the form summit button links to this page:
Your input was received as:
<?php
$firstName = $_REQUEST["firstName"];
$lastName = $_REQUEST["lastName"];
$emailAddress = $_REQUEST["emailAddress"];
$foodBudget = $_REQUEST["foodBudget"];
$utilityBudget = $_REQUEST["utilityBudget"];
$entertainmentBudget = $_REQUEST["entertainmentBudget"];
echo '<br/>';
echo '<br/> Name: ';
echo $firstName;
echo ' ';
echo $lastName;
echo '<br/> Email Address: ';
echo $emailAddress;
echo '<br/> Food Budget: $';
echo $foodBudget;
echo '<br/> Utility Budget: $';
echo $utilityBudget;
echo '<br/> Entertainment Budget: $';
echo $entertainmentBudget;
?>
<?php
require_once 'login.php';
$connection = mysqli_connect(
$db_hostname, $db_username,
$db_password, $db_database);
if(mysqli_connect_error()){
die("Database Connection Failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
); };
$addUser = "INSERT INTO CUSTOMER (CustomerID, CustomerFirstName, CustomerLastName, CustomerEmail,FoodBudget, UtilityBudget, EntertainmentBudget)
VALUES (001,{$connection ->real_escape_string($_POST[firstName])}, {$connection ->real_escape_string($_POST[lastName])},{$connection - >real_escape_string($_POST[emailAddress])}, {$connection ->real_escape_string($_POST[foodBudget])}, {$connection ->real_escape_string($_POST[utilityBudget])}, {$connection ->real_escape_string($_POST[entertainmentBudget])} );";
$upload = mysqli_query($connection, $addUser);
mysqli_close($connection);
?>
When I run the action, and check SELECT * FROM CUSTOMERS; the fields continue to return null. Can someone point me in the right direction?
Try
$firstName = mysqli_real_escape_string($firstName);
$lastName = mysqli_real_escape_string($lastName);
$emailAddress = mysqli_real_escape_string($emailAddress);
$foodBudget = mysqli_real_escape_string($foodBudget);
$utilityBudget = mysqli_real_escape_string($utilityBudget);
$entertainmentBudget = mysqli_real_escape_string($entertainmentBudget);
$addUser = "INSERT INTO CUSTOMER(CustomerID, CustomerFirstName, CustomerLastName, CustomerEmail, FoodBudget, UtilityBudget, EntertainmentBudget) VALUES (001, '" . $firstName . "', '" . $lastName . "', '" . $emailAddress . "', '" . $foodBudget . "', '" . $utilityBudget . "', '" . $entertainmentBudget . "')";
$addUser = "INSERT INTO CUSTOMER (CustomerID, CustomerFirstName, CustomerLastName, CustomerEmail,FoodBudget, UtilityBudget, EntertainmentBudget)
VALUES (001,{$connection ->real_escape_string($_POST[firstName])}, {$connection ->real_escape_string($_POST[lastName])},{$connection - >real_escape_string($_POST[emailAddress])}, {$connection ->real_escape_string($_POST[foodBudget])}, {$connection ->real_escape_string($_POST[utilityBudget])}, {$connection ->real_escape_string($_POST[entertainmentBudget])} );";
You are trying to call function inside double quoted string. It is not possible. You are limited to substitute variables only.
Use string catenation instead.
$addUser = "INSERT INTO CUSTOMER (CustomerID, CustomerFirstName, CustomerLastName, CustomerEmail,FoodBudget, UtilityBudget, EntertainmentBudget)
VALUES (001,'".
$connection->real_escape_string($_POST[firstName]).
"', '".
$connection->real_escape_string($_POST[lastName]).
"','".
$connection->real_escape_string($_POST[emailAddress]).
"', '".
$connection->real_escape_string($_POST[foodBudget]).
"', '".
$connection->real_escape_string($_POST[utilityBudget])}.
"', '".
$connection->real_escape_string($_POST[entertainmentBudget]).
"' );";
Even better, use prepared statements and placeholders.
Also, you can check for errors and show them if any:
if (!$connection->query($addUser)) {
printf("Error: %s\n", $connection->error);
}
You can find that table name is wrong. (because the table name is case sensitive)
Double quoted strings
Prepared statements
Are table names in MySQL case sensitive?
My code is already inserting a data on the database, but only the Primary key(AUTO_INCREMENT) is the only adding. I can't get the date and the text.
Is there something wrong in my code?
Here is my code below:
HTML:
<form action="insertleave.php" method="post">
<label>Date Filed:</label>
<input type="date" name="datefiled">
<label>Date of Leave:</label>
<input type="date" name="leavedate">
</div>
<div class="medium-6 columns">
<label>Reason of Leave:</label>
<textarea rows="8" form="leaveform" name="reason"></textarea>
</div>
<input type="submit" class="expanded button" name="formSubmit" value="File Leave">
</form>
PHP:
<?php
$datefiled = $_POST['datefiled'];
$leavedate = $_POST['leavedate'];
$leavereason = $_POST['leavereason'];
$config = parse_ini_file("phpconfig.ini");
$conn = mysqli_connect($config['host'], $config['username'], $config['password'], $config['dbname']);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO leaves (ID, EmployeeID,DateFiled, LeaveDate, Reason)
VALUES
('$ID','$EmployeeID','$DateFiled','$LeaveDate','$Reason')";
if (mysqli_query($conn, $sql)) {
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
In your text area, you given it a name "reason"
in your post variable, your value is "leavereason"
change the $leavereason = $_POST['leavereason']; to $leavereason = $_POST['reason'];
In you Reason of leave text area name of input is different.
Your variable name are different in your sql query and you are assigning to different variable.
Also your EmployeeID is empty here. there is no input for EmployeeID from html file or you should post it to php file.
Change you php code like this.
<?php
$datefiled = $_POST['datefiled'];
$leavedate = $_POST['leavedate'];
$leavereason = $_POST['reason'];
$config = parse_ini_file("phpconfig.ini");
$conn = mysqli_connect($config['host'], $config['username'], $config['password'], $config['dbname']);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO leaves (ID, EmployeeID,DateFiled, LeaveDate, Reason)
VALUES
('$ID','$EmployeeID','$datefiled','$leavedate','$leavereason')";
if (mysqli_query($conn, $sql)) {
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I am having trouble inserting data into the database 'justrated'. Once the user has entered their business name it should create a new entry in the table 'businesses'. For some reason I cannot get it so that the data is entered in the table. Any advice is gladly appreciated.
CODE:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form>
<input type="text" name="BusinessName" method="POST">
<input type="Submit" value="submit" name="submit" method="POST">
</form>
<?php
if (isset($_POST["submit"])){
//create connection
$conn = new mysqli("localhost", "root", "", "justrated");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO businesses (BusinessName)
VALUES ('".$_POST['BusinessName']."' )";
mysql_query($sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
</body>
</html>
One of your problems is that $_POST['BusinessName'] is empty because the form was submitted using a GET request, not a POST request. The method=POST attribute goes on the <form> element. Eg:
<form method="POST">
<input type="text" name="BusinessName">
<input type="Submit" value="submit" name="submit">
</form>
Also, you should escape the data properly before you insert it into the database:
$sql = "INSERT INTO businesses (BusinessName)
VALUES ('" . $conn->real_escape_string ($_POST['BusinessName']) . "' )";
Furthermore, in these two lines:
mysql_query($sql);
if ($conn->query($sql) === TRUE) {
you try to execute the same query twice using both the MySQL and MySQLi extension. You should remove the first line.
HTML Code
<form method="post" action="test1.php">
<input type="text" name="BusinessName" >
<input type="Submit" value="submit" name="submit" >
</form>
PHP Code
if (isset($_POST["submit"]))
{
//create connection
$conn = new mysqli("localhost", "root", "", "justrated");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO businesses (`BusinessName`)
VALUES ('".$_POST['BusinessName']."' )";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
Don't mix the mysql & mysqli....
Html:
<form method="POST">
<input type="text" name="BusinessName">
<input type="Submit" value="submit" name="submit" >
</form>
Php:
Use
$conn->query($sql); not mysql_query()
hello please check this one i hope this working for you
$sql = "INSERT INTO businesses (`BusinessName`)
VALUES ('".$_POST['BusinessName']."' )";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
After searching through related questions, I still couldn't get this issue resolved. A "registration successful" page is supposed to pop up after a form is submitted but instead, "No database selected" message appears. where did I miss it. here are the codes.
connect.php
<?php
//connect.php
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'esiro';
$connection = mysqli_connect($server, $username, $password, $database);
mysqli_set_charset($connection,"utf8");
?>
signup.php
<?php
//signup.php
include 'connect.php';
include 'header.php';
echo '<h3>Sign up</h3>';
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo
'<form role="form" method="post" action="" class="cover_form">
<div class="form-group">
<label class="labelfield" for="username">User Name:</label><br>
<input class="inputfield" type="text" name="user_name" class="form-control"/><br>
<label class="labelfield" for="pwd">Password:</label><br>
<input class="inputfield" type="password" class="form-control" id="pwd" name="user_pass"><br>
<label class="labelfield" for="pwd"> Confirm Password:</label><br>
<input class="inputfield" type="password" name="user_pass_check" class="form-control" id="pwd"><br>
<label class="labelfield" for="email">Email Address:</label><br>
<input class="inputfield"type="email" class="form-control" id="email" name="user_email">
</div><br>
<input type="submit" class="btn btn-default" value="Complete Registration"/><br>
</form>
';
}
else
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Save the data
*/
$errors = array(); /* declare the array for later use */
if(isset($_POST['user_name']))
{
//the user name exists
if(!ctype_alnum($_POST['user_name']))
{
$errors[] = 'The username can only contain letters and digits.';
}
if(strlen($_POST['user_name']) > 30)
{
$errors[] = 'The username cannot be longer than 30 characters.';
}
}
else
{
$errors[] = 'The username field must not be empty.';
}
if(isset($_POST['user_pass']))
{
if($_POST['user_pass'] != $_POST['user_pass_check'])
{
$errors[] = 'The two passwords did not match.';
}
}
else
{
$errors[] = 'The password field cannot be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo 'Uh-oh.. a couple of fields are not filled in correctly...';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li>' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul>';
}
else
{
//the form has been posted without, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$sql = "INSERT INTO
users(user_name, user_pass, user_email ,user_date, user_level)
VALUES('" . mysql_real_escape_string($_POST['user_name']) . "',
'" . sha1($_POST['user_pass']) . "',
'" . mysql_real_escape_string($_POST['user_email']) . "',
NOW(),
0)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while registering. Please try again later.';
echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
echo 'Successfully registered. You can now sign in and start posting! :-)';
}
}
}
include 'footer.php';
?>
You should Change the script
$result = mysql_query($sql);
Instead of use this
---------------------
$result = mysqli_query($connection,$sql);
And also remove echo mysql_error();
and use this echo mysql_error($connection);
Add this also in instead of mysql_real_escape_string
$sql = "INSERT INTO
users(user_name, user_pass, user_email ,user_date, user_level)
VALUES('" . mysqli_real_escape_string($connection,$_POST['user_name']) . "',
'" . sha1($_POST['user_pass']) . "',
'" . mysqli_real_escape_string($connection,$_POST['user_email']) . "',
NOW(),
0)";