form submitted data is not saved into phpmyadmin - php

I am using the below php code in my localhost on apache server, it shows no error and everything seems going fine when I submitted data in html form but the data is not saved in phpmyadmin table. Anyone can help?
<?php
$servername = 'localhost';
$username = 'root';
$password = 'xxxx';
$database = 'newtable';
$con = mysqli_connect("$servername","$username","$password","$database");
if (! $con){
die('Could not connect: ' . mysqli_error());
}
$sql = "INSERT INTO newtable (firstname, lastname) VALUES ('$_POST[firstname]', '$_POST[lastname]')";
if (! $sql)
{
die('Error: ' . mysqli_error());
}
echo "Record Added Successfully!";
mysqli_close($con);
?>
and html code is:
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" /><br><br>
Lastname: <input type="text" name="lastname" /><br><br>
<input type="submit" />
</form>
</body>
</html>

You forgot to execute your query and please use prepared statement like below
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO newtable (firstname, lastname) VALUES (?, ?)";
$stmt = $con->prepare($sql);
$stmt->bind_param("ss", $firstname, $lastname);
$stmt->execute();

You didn't execute your insert query statement anywhere, so the data was not added.
Replace below line:
if (! $sql)
{
die('Error: ' . mysqli_error());
}
with
if ($mysqli->query($con, $sql) !== TRUE)
{
die('Error: ' . mysqli_error($con));
}

You just write your query forget to execute it
$sql = "INSERT INTO newtable (firstname, lastname) VALUES ('".$_POST['firstname']."', '".$_POST['lastname']."')";
$result=mysqli_query($con,$sql);// execute it
if (! $result)
{
die('Error: ' . mysqli_error($con));// need to pass connection as parameter
}
read
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.query.php
Better to use bind statement to prevent form sql injection
$sql = "INSERT INTO newtable (firstname, lastname) VALUES (?, ?)";
$stmt = $con->prepare($sql);
$stmt->bind_param("ss", $firstname, $lastname);
$stmt->execute();

Thank you guys for you answers, It worked
all I needed to add $result=mysqli_query($con,$sql);
is it a execution of the program?

<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$database = 'newtable'; $con = mysqli_connect("$servername","$username","$password","$database");
if (! $con){ die('Could not connect: ' . mysqli_error()); }
$sql = "INSERT INTO yourTableName (firstname, lastname) VALUES ('".$_POST['firstname']."', '".$_POST['lastname']."')";
if (! $sql) { die('Error: ' . mysqli_error()); } echo "Record Added Successfully!"; mysqli_close($con);
?>
If you are using local host then the db password is blank by default and you need to give your table name in the insert query.

Related

Why does the following not appear to open an SQL connection?

I find that the folowing script hangs for some reason. It will load and PHP doesn't see any errors, but it will not process the data (noting that we are in a context where I have a seperate login database open.)
In process.php we have the following:
<? PHP
//Process the POST data in prepration to write to SQL database.
$_POST['chat_input'] = $input;
$time = date("Y-m-d H:i:s");
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_SESSION['username'];
$servername = "localhost";
$username = "id3263427_chat_user";
$password = "Itudmenif1!Itudmenif1!";
$dbname = "id3263427_chat_user";
$id = "NULL";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = 'INSERT INTO `chat` (`id`, `username`, `ip`, `timestamp`,
`message`) VALUES ('$id','$name', '$ip', '$time', '$input')';
if(mysqli_query($link, $sql)){
mysqli_close($conn);
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
the html form passed to the script above is as follows:
<form action="/process.php" method="post" id="chat">
<b> Send A Message (500 Character Max):</b><br>
<textarea name="chat_input" form="chat" size="500"></textarea>
<input type="submit" value=submit>
</form>
Not sure what's going on with this.
You got the syntax error because you're closing the $sql string before $id with your '.
What is this about your $id variable? With your current code you will insert the String "NULL". If you want to set the sql value null you should use $id = null; or just don't insert any value.
If you want your database to set an id, also leave it blank.
$input = $_POST['chat_input'];
$id = null;
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("ERROR: Could not connect. " . $conn->connect_error);
}
First solution
If this isn't a production code, you could insert the variables directly into the statement, but you should use " instead of ' for your sql string, so you can insert variables and ' without closing the string.
$sql = "INSERT INTO chat (id, username, ip, timestamp, message) VALUES ('$id', '$name', '$ip', '$time', '$input')";
if($conn->query($sql) === true) {
$conn->close();
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $sql. " .$conn->error;
$conn->close();
}
Second solution
A better approach would be a prepared statement.
$stmt = $conn->prepare('INSERT INTO chat (username, ip, timestamp, message) VALUES (?, ?, ?, ?)');
$stmt->bind_param("ssss", $username, $ip, $time, $input);
if($stmt->execute()) {
$stmt->close();
$conn->close();
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $stmt. " . $conn->error;
$stmt->close();
$conn->close();
}
The "s" in bind_param() defines a string at the given position, if you want to insert an integer, use "i" instead.
e.g. bindParam("sis", $string, $integer, $string);

Can't use $_post value as table name for mysql in php

I'm working on a blog right now that aims to display messages to only people it belongs to, so I have a select in html where people can select a person and then it sends it to that table in MySQL.
What I now have in the index.html:
<form action="post.php" method="post">
<label>Naam:</label>
<input type="text" name="name" placeholder="Naam" class="form-control">
<label>Voor wie is dit bericht bestemd?</label>
<select name="portal" class="form-control">
<option id="0">Selecteer</option>
<option id="1">Leerlingen</option>
<option id="2">Docenten</option>
<option id="3">Ouders</option>
<option id="4">Bedrijven</option>
</select>
</div>
<div class="paper col-sm-6">
<label>Email:</label>
<input type="email" placeholder="Email" class="form-control">
<label>Onderwerp:</label>
<input type="textarea" class="form-control" placeholder="Onderwerp" name="subject"/>
</div>
<div class="paper col-sm-12">
<label>Korte informatie:</label>
<input class="form-control" type="textarea" name="short"/>
<label>Volledige informatie</label>
<textarea class="form-control" rows="4" cols="50" name="long"></textarea>
</div>
<div class="paper col-sm-12 text-center">
<div class="col-xs-12" style="height:25px;"></div>
<button class="btn btn-default">Verstuur!</button>
</form>
and this in my post.php:
<?php
$servername = "localhost";
$username = "a1070rik";
$password = "";
$dbname = "portals";
$title = '$_POST[subject]';
$by = '$_POST[name]';
$short = '$_POST[short]';
$long = '$_POST[long]';
$portal = '$_POST[portal]';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO $portal (id, title, by, short, long)
VALUES ('', $title, $by, $short, $long)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When I try to run it it gives me this vague error:
Error: INSERT INTO $_POST[portal] (id, title, by, short, long) VALUES ('', $_POST[subject], $_POST[name], $_POST[short], $_POST[long])
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[portal] (id, title, by, short, long) VALUES ('', $_POST[subject], $_POST[name],' at line 1
Thanks
EDIT:
Thanks everyone that helped,
this code eventually worked for me:
<?php
$servername = "localhost";
$username = "a1070rik";
$password = "";
$dbname = "portals";
$title = $_POST['subject'];
$by_information = $_POST['name'];
$short = $_POST['short'];
$long_information = $_POST['long'];
$portal = $_POST['portal'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO $portal (`id`, `title`, `info_bys`, `info_shorts`, `info_longs`) VALUES ('', '$title', '$by', '$short', '$long')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
$_POST works like an array So you will need to get values from $_POST by his indexs i.e in your case subject,name etc. So Remove ' while assigning the values to variable.
$title = $_POST['subject'];
$by = $_POST['name'];
$short = $_POST['short'];
$long = $_POST['long'];
$portal = strtolower($_POST['portal']);
NOTE : The names 'by,long' are MySQL reserved keywords. So Change them.
Update your SQL from
$sql = "INSERT INTO $portal (id, title, by, short, long) VALUES ('', '$title', '$by', '$short', '$long')";
TO
$sql = "INSERT INTO $portal (`id`, `title`, `info_bys`, `info_shorts`, `info_longs`) VALUES ('', '$title', '$by', '$short', '$long')";
Your sql is vulnerable So use
// prepare and bind
$stmt = $conn->prepare("INSERT INTO $portal (`title`, `info_bys`, `info_shorts`, `info_longs`) VALUES (?, ?, ?, ?)");
$stmt->bind_param($title, $by, $short, $long);
$stmt->execute();
Dont use variables as strings. Keep it organized and fool proof:
<?php
$servername = "localhost";
$username = "a1070rik";
$password = "";
$dbname = "portals";
$title = $_POST['subject'];
$by = $_POST['name'];
$short = $_POST['short'];
$long = $_POST['long'];
$portal = $_POST['portal'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$portal = $mysqli->real_escape_string($portal);
$title = $mysqli->real_escape_string($title);
$by = $mysqli->real_escape_string($by);
$short = $mysqli->real_escape_string($short);
$long = $mysqli->real_escape_string($long);
$sql = "INSERT INTO `".$portal."` (id, title, by, short, long) VALUES ('', '".$title."', '".$by."', '".$short."', '".$long."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Simple PHP Form SQL Insert

I need some help with a very basic issue that I cannot resolve.
A bit of background: I have a PHP form and I would like the information inside the table to insert into my SQL table. For some reason, when I hit submit nothing inserts into the table and I have no idea why. Please help!
This is the PHP Code:
<?php
try
{
$db = new PDO('mysql:host=' . $Database_Host . ';dbname=' . $Database_Database, $Database_Username, $Database_Password);
}catch(PDOException $e){
die("Failed to connect to database! Please check the database settings.");
}
if(isset($_POST['submit'])) {
$result = mysql_query('INSERT INTO requests (song,name,dedicated,time) VALUES ("' . mysql_real_escape_string($_POST['name']) . '", "' . mysql_real_escape_string($_POST['dedicated']) . '", "' . mysql_real_escape_string($_POST['song']) . '", UNIX_TIMESTAMP())');
if ($result) {
echo 'Song requested successfully!<br />';
}
}
?>
This is the HTML Code:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">Request:<br /><br />
Song:<br />
<input type="text" name="song"><br />
Name:<br />
<input type="text" name="name"><br />
Comments:<br />
<input type="text" name="dedicated"><br />
<input type="submit" name="submit" value="Submit" >
</form>
What this is meant to do is insert the request form into the SQL table, however nothing is happening. Any help is appreciated.
Kind Regards,
Edward
You can't mix mysql and PDO like that. You should use a PDO prepared query for the insert.
Also, the order of the values in the VALUES list have to match the column list -- you had the values in the order name, dedicated, song, time instead of song, name, dedicated, time.
<?php
if (isset($_POST['submit'])) {
try
{
$db = new PDO('mysql:host=' . $Database_Host . ';dbname=' . $Database_Database, $Database_Username, $Database_Password);
}catch(PDOException $e){
die("Failed to connect to database! Please check the database settings.");
}
$stmt = $db->prepare('INSERT INTO requests (song,name,dedicated,time) VALUES (:song, :name, :dedicated, UNIX_TIMESTAMP())');
$result = $stmt->execute(array(':song' => $_POST['song'], ':name' => $_POST['name'], ':dedicated' => $_POST['dedicated']));
if ($stmt->rowCount == 1) {
echo "Song requested successfully";
} else {
echo "Song could not be requested";
}
}
You should study about pdo and mysql and then use them ...
just see this simple example with mysql :
<?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);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie#example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
and this one with pdo :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
// insert another row
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
// insert another row
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie#example.com";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
I prefer using pdo
Source : http://www.w3schools.com/php/php_mysql_prepared_statements.asp
NOTE : use prepared statements to avoid sql injection .

PHP fails to post to MySQL Database

I have a formText.php file that contains a form with the following code form code:
<form action="insert.php" method="post">
<p>
<label for="theNames">Name:</label>
<input type="text" name="theName" id="theName">
</p>
<p>
<label for="theCitys">City:</label>
<input type="text" name="theCity" id="theCity">
</p>
<p>
<label for="theAges">Are you over eighteen?(Y/N)</label>
<input type="text" name="theAge" id="theAge">
</p>
<p>
<label for="theDates">Date:</label>
<input type="text" name="theDate" id="theDate">
</p>
<input type="submit" value="Submit">
</form>
Then I have an insert.php file with the following script:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root","phpteste");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security (EDITED)
$theName = mysqli_real_escape_string($link, $_POST['theName']);
$theCity = mysqli_real_escape_string($link, $_POST['theCity']);
$theAge = mysqli_real_escape_string($link, $_POST['theAge']);
$theDate = mysqli_real_escape_string($link, date("Y-m-d h:i:s",$_POST['theDate']));
// attempt insert query execution
$sql = "INSERT INTO tabelateste (id, name, city, overeighteen, date) VALUES (NULL, '$theName', '$theCity', '$theAge', '$theDate')";
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);
?>
My database is called phpteste and my table name is tabelateste.
What am I doing wrong here?
Whenever I click Submit nothing comes up and nothing gets added to the database.
Your post data name fields are wrong. SO you need to change below line:
// Escape user inputs for security
$theName = mysqli_real_escape_string($link, $_POST['theName']);
$theCity = mysqli_real_escape_string($link, $_POST['theCity']);
$theAge = mysqli_real_escape_string($link, $_POST['theAge']);
$theDate = mysqli_real_escape_string($link, date("Y-m-d h:i:s",$_POST['theDate']));
You need to change date to signup_date as per your database table structure.
$sql = "INSERT INTO tabelateste (name, city, overeighteen, signup_date) VALUES ('$theName', '$theCity', '$theAge', '$theDate')";
$sql = "INSERT INTO tabelateste (`name`, `city`, `overeighteen`, `date`) VALUES ('$theName', '$theCity', '$theAge', '$theDate')";
Use this code
I just tested your code (copied and pasted) and it works perfectly under my server configuration (Windows 10 - PHP 5.6) . My best guess is that you have a typo in either the table name or the MySQL configuration.
If you copied this code from another site. Please check that you created the database and the table , and that the MySQL configuration is correct.
A good to check for this kind of mistakes so is to read the PHP error logs
Try it like this maybe
if(isset($_POST['submit']) && !empty($_POST) ){
$theName = $_POST['theName'];
$theCity = $_POST['theCity'];
$theAge = $_POST['theAge'];
$theDate = $_POST['theDate'];
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "phpteste";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tabelateste (name, city, overeighteen, date)
VALUES ('$theName ', '$theCity ', '$theAge ', '$theDate ')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

Sanity check - why does this PHP MySql insert not work?

Can you scan my code below and work out why the form doesn't successfully insert a record in to my MySql table 'users'?
insert.php:
<?php // insert.php
require_once 'login.php';
$con = mysqli_connect($db_hostname, $db_username, $db_password, $db_database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: " . mysqli_connect_error();
}
$sql = "INSERT INTO users (name, email)
VALUES
('$_POST[name]]','$_POST[email]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con;)
?>
index.html:
<html>
<body>
<h1>Hello!</h1>
<form action="insert.php" method="post">
Name: <input type="text" name="name">
Email <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
Login credentials stored in a separate login.php file.
Thanks!
You have an extra square bracket here
('$_POST[name]]',
^------- //Remove this from your SQL Query
You need to switch to PreparedStatements seriously as the above code of yours is directly prone to SQL Injection.
Try to do:
VALUES ('".$_POST[name]."','".$_POST[email]."')";
so... use mysqli_real_escape_string for sql injection as it:
example:
$name = mysqli_real_escape_string($_POST['name']);
and it is mysqli_close($con); not mysqli_close($con;)
For one thing, this line mysqli_close($con;) has a misplaced semi-colon, which should read as mysqli_close($con);
Typo or not, it was posted that way, but I'm not betting my bottom dollar on it.
Plus, your present method is open to SQL injection.
There was a slight syntax error in $_POST[name]] which should have read as $_POST[name] however, as Patrick Evans stated in a comment:
"While that is a typo it wouldn't cause the sql to fail, it would just add a ] to the end of the name in the column."
Use this method instead: (PDO) - it's safer.
<?php
/* Your Database Credentials */
$dbname = 'your_database';
$username = 'username';
$password = 'password';
$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users (name,
email
) VALUES (
:name,
:email)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->execute(array(':name' => $_POST['name'],':email' => $_POST['email']));
if($stmt != false) {
echo "Success!";
} else {
echo "An error occured saving your data!";
}
?>
And your existing, with a few modifications:
<?php // insert.php
require_once 'login.php';
$con = mysqli_connect($db_hostname, $db_username, $db_password, $db_database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: " . mysqli_connect_error();
}
$name=mysqli_real_escape_string($con,$_POST['name']);
$email=mysqli_real_escape_string($con,$_POST['email']);
$sql = "INSERT INTO users (name, email)
VALUES
('$name','$email')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>

Categories