How do you use php to insert into mysql database? - php

So i am having trouble connecting or inserting data into my database. i am using a form to gather information that i need. And then i try to insert into my database. i'm not sure what the problem is but i think i having trouble with the connection. i am using two files to try and accomplish this.
addQuite.html file
<!DOCTYPE html>
<html>
<head>
<title>AddQuote</title>
<link href="styles.css" type="text/css" rel="stylesheet" />
</head>
<body>
<h2> Add a Quote <h2>
<form action="index.php" method="get">
<div>
Quote:<br>
<textarea rows="6" cols="60" name="quote" id="quote">
</textarea>
<br>
Author: <input type="text" name="author" id="author"/> <br>
<input class = "input2" type="submit" value="Save Quotation"/>
</div>
</form>
</body>
</html>
And this is my index.php file which is where i am trying to connect and insert into my database
<!DOCTYPE html>
<html>
<head>
<title>Quotes</title>
<link href="styles.css" type="text/css" rel="stylesheet" />
</head>
<body>
<h1> Quotes </h1>
<form action="addQuote.html">
<input class="input1" type="submit" value="Add Quote"/>
</form>
<?php
//connet to server
$db = new PDO("mysql:host=server;dbname=quotes", "root" , "");
//check connections
if($db===false){
die("ERROR: Could not connect. ");
}
//get name and quote
$name = $_GET['author'];
$quote = $_GET['quote'];
//attemp insert query execution
$sql = "INSERT INTO quotations (name, quote, rating ) VALUES
('$name', '$quote', 0)";
?>
</body>
</html>

have a look in following example
<?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);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

Your query is never executed, add " $db->exec($sql); " to your code.
<?php
//connet to server
$db = new PDO("mysql:host=server;dbname=quotes", "root" , "");
//check connections
if($db===false){
die("ERROR: Could not connect. ");
}
//get name and quote
$name = $_GET['author'];
$quote = $_GET['quote'];
//attemp insert query execution
$sql = "INSERT INTO quotations (name, quote, rating ) VALUES
('$name', '$quote', 0)";
$db->exec($sql);
?>

To insert data into MySQL with PDO you need to use prepared statements. exec() SHOULD NOT be used for inserting data. SQL query needs to be parameterized and data passed separately.
<?php
//connet to server
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$db = new PDO("mysql:host=server;dbname=quotes;charset=utf8mb4", "root", "", $options);
//attempt insert query execution
$db->prepare('INSERT INTO quotations(name, quote, rating ) VALUES(?,?,0)')
->execute([
$_GET['author'],
$_GET['quote']
]);
?>
You should also enable exceptions in PDO with PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, use utf8mb4 charset, and never use root without password in PHP.

Related

PHP form doesn't insert into SQL database

I am trying to test a very simple PHP form that inserts input into an SQL database. The connection works fine, but the data does not appear in the database when I refresh it. I have only two files, an index.html and a process.php.
index.html:
<html>
<head>Testing</head>
<body>
<div id="frm">
<form action="process.php" method=POST>
<p>
<label>Username</label>
<input type="text" id="stuff" name="stuff">
</p>
<p>
<input type="submit" id="btn" value="Login">
</p>
</form>
</div>
</body>
</html>
Process.php:
<?php
$userinput = $_POST['stuff'];
$servername = "localhost";
$username = "root";
$password = "";
$database = "testing";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error)
{
die("connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully ";
echo $userinput;
$sql = "INSERT INTO `entries`(`input`) VALUES ('$userinput')";
}
?>
The problem is that you're not actually running the query. You just assigned the query string to a variable, so it's not being executed in MySQL.
Your code is vulnerable to SQL injection, so I'm proposing a solution:
<?php
$userinput = $_POST['stuff'];
$servername = "localhost";
$username = "root";
$password = "";
$database = "testing";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error)
{
die("connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully ";
echo $userinput;
$sql = "INSERT INTO `entries` (`input`) VALUES (?)";
if ($stmt = $conn->prepare($sql)) { // Prepare statement
$stmt->bind_param("s", $userinput); //Bind the string (s), with the content from $userinput to the statement marker (?)
$stmt->execute(); // Run (execute) the query
$stmt->close(); //clean up
}
This code should work and also keep you secure from SQL injections.
Haven't tested it fully but I fixed your query.
$sql = mysqli_query($conn, "INSERT INTO entries (input) VALUES ('$userinput')");
also change the post part to: <form action="process.php" method="POST">
That should fix the problem for you
Also make sure you use the function: mysqli_real_escape_string to escape malicious user input to prevent SQL injection.
Another thing: you could change localhost to 127.0.0.1. I think this is more reliable although it's the same in most cases.
Your code is not submitting the query to the database, it is opening the connection but not submitting the query, see below to the submit query request if you use mysqli in PHP
... else {
# this submits the query
$conn -> query ($sql);
}
you need to take function mysqli_query of mysqli that will take parameter as connection object like $conn and 2nd parameter will be sql query to execute.
like this
$sql = mysqli_query($conn, "INSERT INTO entries (input) VALUES ('$userinput')");
to prevent from sql injection you must use PDO because PDO use paramBind to protect injection .

Error while filling a mysql database with data from php/html

I created this for one of my projects. We have a webshop where users can enter their credentials and order products. The current solution puts all the data into a .csv-file and I was tasked with creating a mysql database as a new solution.
I added a simple HTML insert for the user to enter his name, but if I try to run the script I get a syntax error for line 19. I'm new to programming and therefore not sure what the error is here.
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "localhost";
$password = "";
$dbname = "test"
// create a variable
$Vorname=$_POST['Vorname'];
$Nachname=$_POST['Nachname'];
//Execute the query
mysqli_query($connect "INSERT INTO tbl_bestellungen(Vorname,Nachname)
VALUES('$Vorname','$Nachname')");
<?php include 'database.php';>
if(mysqli_affected_rows($connect) > 0){
echo "<p>Bestellung erfasst</p>";
} else {
echo "Bestellvorgang fehlgeschlagen<br />";
echo mysqli_error ($connect);
<h2>Text Input</h2>
<form>
Vorname:<br>
<input type="text" name="Vorname">
<br>
Nachname:<br>
<input type="text" name="Nachname">
<input type="submit" name="button1" value="Senden">
</form>
</body>
</html>
Thanks in advance.
Well you should do like this way:
$servername = "localhost";
$username = "localhost";
$password = "";
$dbname = "test"
$dbConn = mysqli_connect($servername, $username, $password, $dbname);
if(!$dbConn){
echo "No Db connected";
}
//above connection code should be in a separate file and include in all files or header
$Vorname=$_POST['Vorname'];
$Nachname=$_POST['Nachname'];
$query = "INSERT INTO tbl_bestellungen (Vorname,Nachname)
VALUES('$Vorname','$Nachname')";
or you can set query like
$query = "INSERT INTO tbl_bestellungen (Vorname,Nachname)
VALUES('".$Vorname."','".$Nachname."')";
if($dbConn->query($query)){
echo "Record inserted !";
}else{
echo "Record cannot be inserted !";
}

Empty database records after a form submit

I am trying to save a form data into my database but I get just empty records.
I tryied many solutions but I really don't know where's the bug. I am getting crazy!
This is my form:
<head>
<form action="uploadall.php" method="post">
Name: <input type="text" name="name"><br>
Autore: <input type="text" name="author"><br>
Descrizione: <textarea id="editordescription" name="description" cols="45" rows="15">
</textarea>
<script>
CKEDITOR.replace( 'editordescription' );
</script>
<br>Misure: <input type="text" name="misure"><br>
Data: <input type="text" name="date"><br>
<input type="hidden" name="status" value="Disattivo" size="20">
<input type="submit">
</form>
And this is my PHP script to save records:
<?php
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysqli_real_escape_string(htmlspecialchars($_POST['name']));
$author = mysqli_real_escape_string(htmlspecialchars($_POST['author']));
$description = mysqli_real_escape_string(htmlspecialchars($_POST['description']));
$misure = mysqli_real_escape_string(htmlspecialchars($_POST['misure']));
$date = mysqli_real_escape_string(htmlspecialchars($_POST['date']));
$status = mysqli_real_escape_string(htmlspecialchars($_POST['status']));
}
$servername = "xxxxxxx";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxxxx";
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);
$sql = "INSERT INTO exposition (name, author, description, misure, date, status)
VALUES ('$name', '$author', '$description', '$misure', '$date', '$status')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
And this is what I get in my database at the moment:
First, you are mixing the mysql api's at somepoint you are using mysqli_* at some point u using mysql_* They don't mix. And mysql_* functions are depreciated they no longer supported by later versions of php. better use mysqli or pdo. this mysql_real_escape_string() or mysqlo_real_escape_string() is not safe enough to prevent you against sql injections. solution is simple better start using mysqli prepared statements or pdo prepared statements.
another error : <input type="text" name="name"> <input type="text" name="name"> these two inputs fields have the same name attribute php will only read one. and you will get an undefined index here $misure = $_POST['misure']; You need to activate error reporting while you are still developing so you can see your errors and notices:
add this at the top of every php page : ini_set('display_errors', 1);
error_reporting(E_ALL);
also date date is a reserved word for mysql so you better use something else for your column name or add backslashes date
Oh and your code never execute here :
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$author = mysql_real_escape_string(htmlspecialchars($_POST['author']));
$description = mysql_real_escape_string(htmlspecialchars($_POST['description']));
$misure = mysql_real_escape_string(htmlspecialchars($_POST['misure']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$status = mysql_real_escape_string(htmlspecialchars($_POST['status']));
}
Why is that? because you do not have POST value with the submit attribute name. <input type="submit"> see? your submit does not have a name attribute. therefore. This means
all this :
VALUES ('$name', '$author', '$description', '$misure', '$date', '$status')"; These are all undefined variables. I'm surprised why doesn't your server tell you that, with that error reporting enable you will get all those.
This is what u need to do to solve that :
Your html side.
<form action="uploadall.php" method="post">
Name: <input type="text" name="name"><br>
Autore: <input type="text" name="author"><br>
Descrizione: <textarea id="editordescription" name="description" cols="45" rows="15">
</textarea>
<script>
CKEDITOR.replace( 'editordescription' );
</script>
<br>Misure: <input type="text" name="misure"><br>
Data: <input type="text" name="date"><br>
<input type="hidden" name="status" value="Disattivo" size="20">
<input type="submit" name="submit">
</form>
uploadall.php
<?php
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])) {
$servername = "xxxxxxx";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//check your inputs are set and validate,filter and sanitize
$name = $_POST['name'];
$author = $_POST['author'];
$description = $_POST['description'];
$misure = $_POST['misure'];
$date = $_POST['date'];
$status = $_POST['status'];
//prepare and bind
$sql = $conn->prepare("INSERT INTO exposition (name, author, description, misure, date, status)
VALUES (?,?,?,?,?,?)");
$sql->bind_param("ssssss", $name, $author, $description, $misure, $date);
if ($sql->execute()) {
echo "New record created successfully";
} else {
//you have an error
}
$conn->close();
}
?>
That's all good luck.
Update :
I corrected errors you told me and I am using PDO now but it still
doesn't work
I read that from your comments above, but you not telling us what the errors are, but I believe they are the ones I highlighted above.
with PDO this is how u will achieve your goal :
<?php
//connection
$servername = 'XXXXXXXXXXXXX';
$dbname = 'XXXXXXXXXXXXX';
$username = 'XXXXXXXXXXXXXX';
$password = 'XXXXXXXXX';
$charset = 'utf8';
$dsn = "mysql:host=$servername;dbname=$dbname;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbh = new PDO($dsn, $username, $password, $opt);
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])) {
//check your inputs are set and validate,filter and sanitize
$name = $_POST['name'];
$author = $_POST['author'];
$description = $_POST['description'];
$misure = $_POST['misure'];
$date = $_POST['date'];
$status = $_POST['status'];
//prepare and bind
$stmt = $dbh->prepare("INSERT INTO exposition (name, author, description, misure, date, status)VALUES (?,?,?,?,?,?)");
if ($stmt->execute(array($name,$author,$description,$misure,$date,$status))) {
echo "New Record inserted success";
}
}
?>
Variable name problem E.g
Name: <input name="name">
and :
Misure: <input name="name">.This must be different.
Again, <input type="submit"> should be <input type="submit" name="submit">.
Hope, it will be helpful.
The variables you are using inside your INSERT Query are out of scope from the first if block where you are getting the data from your form. If the variables are initialized before the first if block it might work. like below..
$name = ""; $author = "";$description = "";$misure = "";$date = "";$status=";
if (isset($_POST['submit'])){ // as is}

How do I validate this php form?

I have a simple html form that looks like this
<form action="insert.php" method="post">
Name: <input type="text" name="name"><br>
Password: <input type="text" name="pw"><br>
<input type="submit" value="log in">
</form>
What I need to do with this is check the values that are submitted in this form against those in a simple database I have created. The database is name is userdb, and in it I have created a simple table called 'users', with two columns called name and password.
I am able to connect to the database correctly with
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Now I'm confused with (probably the most important bit) where I have to validate the form against some values in the database.
I have created a name and password entry in phpmyadmin, for name='eric' and password='123456'.
I'm just not sure how to check it using the form?
Is it something like this?
$sql = "INSERT INTO `userdb`.`users` (`name`, `password`) VALUES ($name, $pw);";
$name and $pw are values that I got from the form name attributes.
It tells me I have undefined variables though so obviously I've got it wrong here.
Any help?
*edit here is the full code:
index.php
<html>
<head>
<style>
#main
{
width: 700px;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<div id="main">
<?php
$name = "";
$pw = "";
?>
<form action="insert.php" method="post">
Name: <input type="text" name="name"><br>
Password: <input type="text" name="pw"><br>
<input type="submit" value="log in">
</form>
</div>
</body>
</html>
insert.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$con=mysqli_connect("localhost","userdb","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "you are connnected";
}
$sql = "INSERT INTO `userdb`.`users` (`name`, `password`) VALUES ($name, $pw);";
?>
</body>
</html>
Your POST variables are in the wrong file. Take them out of index.php and place them in insert.php as so:
You're also storing passwords in plain text, which is not recommended. Use PHP's password_hash() function if your PHP version is 5.5. Otherwise, use crypt() or bcrypt()
Sidenote: There is a password compatibility pack available here for the password_* functions.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$con=mysqli_connect("localhost","userdb","","");
$name=$_POST['name']; // <-- right there
$pw = $_POST['pw']; // <-- right there
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "you are connnected";
}
$sql = "INSERT INTO `userdb`.`users` (`name`, `password`) VALUES ('$name', '$pw')";
?>
</body>
</html>
If you want to check for successful insert, do:
$sql = "INSERT INTO `userdb`.`users` (`name`, `password`) VALUES ('$name', '$pw')";
if (mysqli_query($con,$sql))
{
echo "Database updated successfully";
}
else
{
echo "Error: " . mysqli_error($con);
}
Footnotes:
For added security, change:
$name=$_POST['name']; // <-- right there
$pw = $_POST['pw']; // <-- right there
to:
$name=mysqli_real_escape_string($con,$_POST['name']);
$pw = mysqli_real_escape_string($con,$_POST['pw']);
Login method: (Sidenote: Use the password storage methods shown at the top if possible).
If you want to use it as a login method, you can use something to the effect of:
$con = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die("could not connect");
$user = mysqli_real_escape_string($con,$_POST['name']);
$pass = mysqli_real_escape_string($con,$_POST['pw']);
$query = "SELECT * FROM your_table WHERE name='$user' AND password='$pass'";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
if($row["name"]==$user && $row["password"]==$pass){
echo "You are a validated user.";
}
else{
die("Sorry.");
}
$sql="SELECT * FROM userdb WHERE name='$name' LIMIT 1";
Then fetch the result and check if the password is equal to the password you have.
Next thing you want is to return something, and also to actually log the user in do:
$_SESSION['userid'] = $userid;
Or store whatever you want^. Then check if that exists in all your other pages to determine if the user is logged in.
EDIT: Also it seems like it's needed to add - you're not storing your passwords securely, and you're also not sanitizing your strings properly (against SQL injections). Might want to look into that ^_^.
EDIT 2: Oh yeah, for your problems - variables are undefined because you have to get them using $_POST['']. Inside the '', put the name of the variable you're expecting. $_POST['name'] to get the name, for example.
I would recommend you to use the PHP Data Objects handle the data.
I am not quite sure what exactly you want. You want to make a login page or a signup page?
//connect database
$dsn='mysql:dbname=userdb;host=localhost';
$dbu=''; //YOUR DATABASE USERNAME GOES HERE
$dbp=''; //YOUR DATABASE PASSWORD GOES HERE
try {
$dbh=new PDO($dsn,$dbu,$dbp);
} catch (PDOException $e) {
echo 'Connection failed: '. $e->getMessage();
}
if it's a login page, using this:
//check name and password
$sth=$dbh->prepare('SELECT 1 FROM users WHERE name = ? AND password = ?');
$sth->execute(array($_POST["name"], $_POST["pw"]);
$row=$sth->fetchAll(PDO::FETCH_ASSOC);
if (count($row) == 1){
echo "Correct name and password";
} else {
echo "Wrong name or password";
}
if it's a signup page, using this:
//insert name and pass
$sth=$dbh->prepare('INSERT INTO users (name, password) VALUES (?,?)');
$sth->execute(array($_POST["name"], $_POST["pw"]);

Error when saving to MySQL when field contains ' character

I have a form with PHP that saves a variable to a MySQL database. That form worked on a VPS, but when trying it on another VPS it gives an error when trying to write to the database when the field contains a ' character. So the same PHP code works on 1 VPS when the field contains a ' character, but not on the other VPS.
Here it works: http://www.zoekmachineoptimalisatie.us/test.php
and here (it's the other VPS) it gives an error: http://www.onzebruidsfotograaf.nl/test.php
My form:
<?php
$hostname = "localhost"; //host name
$dbname = "xxxxxxxx"; //database name
$username = "xxxxxxxx"; //username you use to login to php my admin
$password = "xxxxxxxx"; //password you use to login
$conn = new MySQLi($hostname, $username, $password, $dbname);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Untitled Document</title>
</head>
<body>
<?php
if (isset($_POST['Submit'])) { //if the submit button is clicked
$title = $_POST['updatetitle'];
$bookid = 1;
$update = "UPDATE test SET Title='$title' WHERE BookID = " . $bookid;
$conn->query($update) or die("Cannot update"); //update or error
}
?>
<?php
$bookid = 1;
$sql = "SELECT * FROM test WHERE BookID = '" . $bookid . "'";
$result = $conn->query($sql) or die(mysql_error());
$query = getenv(QUERY_STRING);
parse_str($query);
?>
<h2>Update Record <?php echo $bookid;?></h2>
<form action="" method="post">
<?php
while ($row = $result->fetch_assoc()) {
?>
<textarea name="updatetitle" cols="100" rows="30"><?php echo $row['Title']; ?></textarea>
<table border="0" cellspacing="10">
<tr>
<td><INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit"></td>
</tr>
</table>
<?php
}
?>
</form>
<?php
if ($update) { //if the update worked
echo "<b>Update successful!</b>";
}
?>
</body>
</html>
An unescaped quote in your query will produce a syntax error. Instead of building the SQL fully your own, make use of SQL variables for your PHP variables with a Prepared Statement:
if (isset($_POST['Submit'])) { //if the submit button is clicked
$title = $_POST['updatetitle'];
$bookid = 1;
$update = $conn->prepare('UPDATE test SET Title = ? WHERE BookID = ?;');
$update->bind_param('sd', $title, $bookid);
$update->execute();
}
One of your servers has Magic Quotes enabled and the other doesn't. Magic Quotes is now considered undesirable and is deprecated, it automatically escapes input. You should turn off Magic Quotes and use a parameterised query/prepared statement instead - then there is no need to escape anything and it prevents SQL Injection.
Paramterised queries are supported by the MySQLi and PDO APIs.
because the single quote breaks the query statement. In order to prevent from it or from SQL Injection you need to use PDO or MySQLI extension. For more infor, see the article below
How can I prevent SQL injection in PHP?

Categories