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

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);
?>

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);

Mysql configured correctly for remote connection but php code failing connection?

I went through the grueling process of figuring out how to bind the correct address in the config file and connect mysql to my remote server. Yesterday it was working with different code and now it's not connecting. I'm getting the die "connection failed: " but its not showing me the connect_error as I called for so cant even figure out the issue? Does anyone see something wrong with my code? NOTE: I know this is unsafe and I usually do prepared statements but just trying to work with connection to the db issue now.
<?php
$server = "174.---.--.187";
$username = "dylanto";
$pass = "------";
$db = "survey";
//$port = 3306;
//create connection
$conn = new mysqli($server, $username, $pass, $db);
//check connection
if (!$conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
$user = $_POST['user'];
$pass = $_POST ['pass'];
$sql = "insert into login (user, pass) values ('$user','$pass')";
if ($conn->query($sql)==TRUE) {
echo "Account created";}
else {echo "something went wrong";}
$con->close;
?>
Html code:
<html><head><title>Log-in</title>
<link rel="stylesheet" type="text/css" href="sytle.css"></head>
<body>
<center><u><strong><h2>Login</h2></u></strong></center>
<br />
<center>
<form action="signup_process.php" method="POST">
Pick Username: <br>
<input type ="text" name = "user"><br>
Pick Password:<br>
<input type ="password" name ="pass"><br>
<input type="submit" name="submit" value="Sign-up">
</form></center>
</body>
</html>
From
if (!$conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
To:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Since if ($conn->connect_error) = If any error and if (!$conn->connect_error) if no error.
For prepared statement :
From:
$sql = "insert into login (user, pass) values ('$user','$pass')";
if ($conn->query($sql)==TRUE) {
echo "Account created";}
else {echo "something went wrong";}
To :
//sanityze POST
$user = trim(mysqli_real_escape_string($conn, htmlspecialchars($_POST['user'], ENT_QUOTES, 'UTF-8')));
$pass = trim(mysqli_real_escape_string($conn, htmlspecialchars($_POST['pass'], ENT_QUOTES, 'UTF-8')));
//use prepared
$stmt = $conn->prepare("insert into login (user, pass) values (?,?)");
//bind parameter
$stmt->bind_param("ss", $user, $pass)
$stmt->execute();
//then check

I GET "No database selected" ERROR even that is selected

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>

form submitted data is not saved into phpmyadmin

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.

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;
}
}

Categories