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;
}
}
Related
I'm trying to insert new record to SQL database using PHP from a HTML form.
I made a form using Post method
<form name="CreatNewMCQ" action="create.php" method="POST">
with a button to submit
<button type="submit" form="CreateNewMCQ">CREATE</button>
what I want to do is when I press the button, it will call create.php which is
<?php
$servername = "localhost";
$user = "admin";
$pass = "admin";
$dbname = "examples";
// Create connection
$conn = new mysqli($servername, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_POST['id'];
$name = $_POST['name'];
$year = $_POST['year'];
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, $name, $year)";
if ($conn->query($sql) === TRUE) {
echo "Tạo mới thành công";
} else {
echo "Lỗi: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
then insert data from form to SQL database (id, name, year from the form).
I got some errors in SQL syntax. What mistake did I make?
Make sure all post values are getting correctly. You should make a condition check before inserting the data, For ex:
$id = isset($_POST['id']) ? $_POST['id'] : '';
$name = isset($_POST['name']) ? $_POST['name'] : '';
$year = isset($_POST['year']) ? $_POST['year'] : '';
if($id && $name && $year){
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, '$name', '$year')";
}else{
return "required fields are missing";
}
NB: Please post your html if possible.
try this:
<?php
/* Attempt MySQL server connection.*/
$servername = "localhost";
$user = "admin";
$pass = "admin";
$dbname = "examples";
$link = mysqli_connect($servername, $user, $pass, $dbname);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$id = $_POST['id'];
$name = $_POST['name'];
$year = $_POST['year'];
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, '$name', '$year')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
HTML Form :
<html>
<form name="test" method="post">
Enter name:<input type="text" name="name"/> <br>
Enter year :<input type="text" name="year"/><br>
<input type="submit" name="save" value="save" />
</form>
</html>
php code :
<?php
$conn=mysql_connect("localhost","root","passward");
$select_db=mysql_select_db("Atul",$conn);
if($conn)
{
echo "connected";
}
else
{
echo "Please try again";
}
if(isset($_POST['save']))
{
$name=$_POST['name'];
$year=$_POST['year'];
$insert_record="insert into test (name,year) values("$name","$year");
$result=mysql_query($insert_record);
if($result)
{
echo "Record inserted successfully";
}
else
{
echo "please try again";
}
}
?>
I'm new to database development, and really struggling with formatting. For the life of me, I can't seem to flush out the errors. I have a simple html form that I am passing to my php file to submit to my local host. For whatever reason, I can't seem to add $_POST in the values. I'm sure I'm missing something, maybe someone on here can help.
Thanks in advance!
<form method="post" action="demo.php">
<input type="text" id="fname">
<input type="text" id="lname">
<input type="text" id="email">
<input type="submit" value="Go!">
</form>
My demo.php is:
<html>
<body>
<?php
$servername = "localhost";
$username = "myuser";
$password = "";
$dbname = "my_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql =
'INSERT INTO
test_tb (firstname, lastname, email)
VALUES
(
"echo $_POST['fname']",
"echo $_POST['lname']",
"echo $_POST['email']"
)';
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</body>
</html>
First change your form..
Look at your inputs; take this one for example:
<input type="text" id="fname">
This is missing the name attribute therefore, it won't be correctly set when you submit the form; it must be like so:
<input type="text" id="fname" name="fname">
Secondly, if you want to concatenate a string, you don't use echo, echo is used for outputting text. To attach strings together in PHP you should read the manual page on string operators
Thirdly and most importantly;
Use prepare to input your data. Never pass $_POST directly into your query.
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql =
'INSERT INTO
test_tb (firstname, lastname, email)
VALUES
(
?,
?,
?
)';
//use ->prepare in favour of ->query
if ($stmt = $conn->prepare($sql)) {
//bind your inputs
$stmt->bind_param('sss',$_POST['fname'],$_POST['lname'],$_POST['email']);
//execute the prepared query
if($stmt->execute()){
echo "New record created successfully";
}
//You had a random ';' here that I've commented out??
//;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
echo "</br>Stmt error: ".$stmt->error();
}
Im new in MySql and PHP and im trying to make a CRUD but everytime i try to insert data into table called "studenti" i get the error that i didnt select a database but i selected a database with mysqli_select_db($con, "d_base");
Somebody please help me cuz i dont understand why its not workin'
Here is the code;
$id = $_POST['ID'];
$nota = $_POST['Nota'];
$emri = $_POST['Emri'];
$mbiemri = $_POST['Mbiemri'];
$servername = "localhost";
$dbname = "d_base";
// 1.Create connection
$con = mysqli_connect("localhost","d_base");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!mysqli_query($con,"INSERT INTO studenti (id, nota, emri, mbiemri) VALUES ('$id', '$nota','$emri','$mbiemri')"))
{
echo("Error description: " . mysqli_error($con));
}
// Perform queries
mysqli_select_db($con, "d_base");
mysqli_query($con,"INSERT INTO studenti (id, nota, emri, mbiemri) VALUES ('$id', '$nota','$emri','$mbiemri')");
mysqli_close($con);
Before all that if you are a begginer go straight on PDO or use mysqli with prepared statements its safer.
Here is example how your php and html form must look like and work.
First you must check if submit button is pressed, if its pressed read values form form $_POST variables.
Second thing you must escape injection to your mysql by using function mysqli_real_escape_string().
After that try to insert query and check for error, if there is no error query will be inserted successfully.
PHP code
<?php
// set error report ; 1 = on | 0 = off
error_reporting(1);
$db_host = "localhost"; // host
$db_user = "root"; // database username
$db_pass = ""; // database password
$db_name = "d_base"; // database name
// 1.Create connection
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// if form is submited
if (isset($_POST['submit']))
{
// escape post variables
$id = mysqli_real_escape_string($con, $_POST['ID']);
$nota = mysqli_real_escape_string($con, $_POST['Nota']);
$emri = mysqli_real_escape_string($con, $_POST['Emri']);
$mbiemri = mysqli_real_escape_string($con, $_POST['Mbiemri']);
// make query
$query = mysqli_query($con, "INSERT INTO studenti (id, nota, emri, mbiemri VALUES ('$id', '$nota', '$emri', '$mbiemri')")
// check for query
if (!$query)
{
echo "Error description: " . mysqli_error($con);
}
else
{
echo "Query inserted.";
}
// close connenction
mysqli_close($con);
}
?>
<form action="" method="post">
<input type="text" name="ID" placeholder="Id"><br />
<input type="text" name="Nota" placeholder="Nota"><br />
<input type="text" name="Emri" placeholder="Emri"><br />
<input type="text" name="Mbiemri" placeholder="Mbiemri"><br />
<input type="submit" name="submit" value="Submit form">
</form>
So currently, this is the code I have
index.php:
<form action="insert.php" method="post">
Comments:
<input type="text" name="comment">
<input type="submit">
</form>
insert.php:
<?php
include ('index.php');
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "x", "", "comment_schema");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','$comment')";
// attempt insert query execution
if(mysqli_query($link, $sql)){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
When I do echo $comment, nothing gets printed out. However, if I do something like echo "hi" it works. I think for some reason the $_POST is not being recognized. Any suggestions to make this work or if I'm doing it wrong.
My goal is to take a user input and insert into a database on phpmyadmin. Currently, it is able to insert, however it inserts an empty value. I only have two columns in my database. An ID and a Comment column. The ID is auto incremented. The comment is what I get from the user.
Check Once what is your data type of comment in database.(I prefer Varchar()).
Try this as it is:-
<form action="insert.php" method="POST">
Comments:
<input type="text" name="comment"/>
<input type="submit" name="submit" value="submit">
</form>
<?php
include ('index.php');
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect("localhost", "x", "", "comment_schema");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','$comment')";
if(mysqli_query($link, $sql)){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
try this
<?php
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$link = mysqli_connect($host, $user, $password, $db);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
$sql = "INSERT INTO parentComment(ID, Comment) VALUES(NULL,'$comment')";
// attempt insert query execution
if(mysqli_query($link, $sql)){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
Use below code:-
include ('index.php');
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect("localhost", "x", "", "comment_schema");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_POST["comment"])){
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
// Escape user inputs for security
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','$comment')";
$result = mysqli_query($link, $sql);
// attempt insert query execution
if($result){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}else{
die('comment is not set or not containing valid value');
}
Hope it will help you :-)
Some debugging suggestions:
var_dump($_POST); // before mysqli_real_escape_string
var_dump($comment); // after mysqli_real_escape_string
mysqli api may not work well! Fix the query like
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','".$comment."')";
echo $sql; // check your sql syntax
echo mysqli_error($link); // do you have error
Look at your .htaccess file see if you have <Limit POST> tag
Remove this line include ('index.php');. Supposedly, these two files are in one folder. So just run index.php . Tried your code without that line and it worked for me.
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();
?>