PHP not inserting into tables - php

I'm having trouble getting a practice signup form to submit data to my database ...
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$name = $email = $password = "";
?>
<form method="post">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Password: <input type="text" name="password">
<br><br>
<input type="submit" value="Submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
function fix_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>

In addition to Ugur's answer, you are mismatching mysqli commands and mysql commands. Here's how to do this in an object oriented fashion:
// create mysqli database object
$mysqli = new mysqli_connect("localhost","username","password","database");
// store your query in a variable. question marks are filled by variables
$sql = "INSERT INTO table_name ('username','password') VALUES (?,?)";
// prepare command uses $sql variable as query
$stmt = mysqli->prepare($sql);
// "ss" means your 2 variables are strings, then you pass your two variables.
$stmt->bind_param("ss",$name,md5($password));
// execute does as it seems, executes the query.
$stmt->execute();
// then print your success message here.
Using prepared statements removes the need to sanitize user input, as harmful input is not substituted into the query directly. For more reading:
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
There are some good tips for using prepared statements in many different scenarios, as well as towards the bottom, there is an explanation on how prepared statements prevent SQL injection.

Missing table name
mysql_query("INSERT INTO ...... ('username','password') VALUES ('$name', md5('$password'))");

You're mixing mysql_* with mysqli_* functions, i.e.: mysqli_connect and mysql_query and you're wrapping your column names in quotes, plus you're missing the table name to insert into.
Try the following, fixed code:
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysqli_query("INSERT INTO `your_table` (`username`,`password`) VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
You're also using password storage technology that dates back to 1996. MD5 is no longer considered safe to use.
I suggest you look into PHP's password function: http://php.net/password
And if you're having problems with your fix_input() function, you should consider using the mysqli_real_escape_string() function.
then setting up a DB connection while passing a variable to it.
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
and instead of using:
$name = fix_input($_POST["name"]);
use the following:
$name= mysqli_real_escape_string($db, $_POST['name']);
and do the same for the rest.

you don't have table name in your query! also do not use quotation in your column name :)
you have mixed up mysqli and mysql.
Change
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
to
mysqli_query("INSERT INTO yoour_table(username',password) VALUES ('$name', md5('$password'))");

Related

Can't insert string (lettters) into mysql . Numbers work fine

So here I come with another problem. I can't push strings into mysql table. If I use numbers it works fine. If I try to insert text as value it works as well. No luck with text that was put in textboxes in html.
$current_user = wp_get_current_user();
$hostname = "XXX";
$username = "XXX";
$password = "XXX";
$dbname= "XXX";
$connect=mysqli_connect($hostname, $username, $password, $dbname);
$sql="insert into wypozyczenia (czy_wypozyczony, sn, model) values (2,"
.mysql_escape_string($_POST['SN']).",
".mysql_escape_string($_POST['model']).")";
if ($current_user->ID=2)
{
?><form name="form" method="post" >
Model:</br>
<input type="text" name="model"></br>
Numer Seryjny</br>
<input type="text" name="SN"></br>
<input type="submit" name="button1" value="Send">
</form>
<?php
if(isset($_POST["button1"])){
$model=$_Post["model"];
$SN=$_Post["SN"];
?> <pre><?php var_dump($_POST); ?></pre><?php
mysqli_query($connect,$sql);}}
Try adding single quote before the double quote, like the following:
$sql = "insert into wypozyczenia (czy_wypozyczony, sn, model) values (2,
'".mysql_escape_string($_POST['SN'])."',
'".mysql_escape_string($_POST['model'])."')";
You can use sprintf for beauty code or learning prepare statement in PHP PDO
$sql = sprintf("insert into wypozyczenia (czy_wypozyczony, sn, model) values (2,'%s','%s')"
,mysql_escape_string($_POST['SN'])
,mysql_escape_string($_POST['model']));

adding new mySQL table row with PHP doesn't work

I got a little form:
<form id="plannerform" action="save.php" method="post">
<input id="plannername" placeholder=" " type="text" autocomplete="off" name="plannername">
<input id="plannersubmit" type="submit" value="eintragen">
</form>
As you can see there is the action="save.php" and method="post" on the text-input there is name="plannername".
And thats my php:
$con = mysql_connect("myHost","myUser","myPW");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB", $con);
$sql="INSERT INTO anmeldungen (FR_PM)
VALUES ('$_POST[plannername]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
The FR_PM is one column of my table. But when I press submit, not even a new row gets created. Nothing happens.
But when I call my php with "mywebsite.com/save.php" it adds a new row in my table (with no value at "FR_PM", what's pretty obvious)
What do I do wrong?
one of the things that you need to learn if you are a beginner, you should try by all means to stay away from using mysql_* function this is depreciated and its no longer supported in php. instead use mysqli_* with prepared statements, or use PDO prepared statements.
prepared statments make you code looks clean and its easy to debug.
this is you example with prepared statements.
<form id="plannerform" action="save.php" method="post">
<input id="plannername" placeholder=" " type="text" autocomplete="off" name="plannername">
<input id="plannersubmit" type="submit" value="eintragen" name="submit">
</form>
save.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit'])) {
if (empty($_POST['plannername'])) {
die("Enter plannername");
} else {
// prepare and bind
$stmt = $conn->prepare("INSERT INTO anmeldungen (FR_PM) VALUES (?)");
$stmt->bind_param("s", $_POST['plannername']);
if ($stmt->execute()) {
echo "New records created successfully";
} else {
echo "Could not insert record";
}
$stmt->close();
}
}
?>
The reason I used prepared statements :
Prepared statements reduces parsing time as the preparation on the
query is done only once (although the statement is executed multiple
times)
Bound parameters minimize bandwidth to the server as you need send
only the parameters each time, and not the whole query
Prepared statements are very useful against SQL injections, because
parameter values, which are transmitted later using a different
protocol, need not be correctly escaped. If the original statement
template is not derived from external input, SQL injection cannot
occur.
But when I call my php with "mywebsite.com/save.php" it adds a new row
in my table (with no value at "FR_PM", what's pretty obvious)
What do I do wrong?
Well do prevent that from happening you need to check if the form was submitted before you can actual process any thing.
Note: If we want to insert any data from external sources (like user input from a form ), it is very important that the data is sanitized
and validated. always treat input from a form as if its from a very
dangerous hacker
change your insert query:
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('".$_POST["plannername"]."')";
Or
$plannername = $_POST["plannername"];
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('".$plannername."')";
Also, use "name"= and not "id"= in the HTML form.
This is usually misleading when working with forms and HTTP POST method.
you may try
$value = $_POST['plannername'];
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('{$value}')";

HTML/PHP form doesn't insert data to MySQL Database [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 1 year ago.
I am new to PHP, and I have been trying to make a small Homework Organiser Application.
The idea is that you can input a Subject and Description and it will be added to a MySQL Database (that's it for now).
I have created a html form:
<form action="insert.php">
<label for="subj">Subject:</label>
<br>
<input type="text" name="subj">
<br>
<label for="desc">Description:</label>
<br>
<input type="text" name="desc">
<br>
<input type="submit" value="Submit" name="submit">
</form>
and some php code:
<?php
$subject = $_POST['subj'];
$description = $_POST['desc'];
$subject = mysql_real_escape_string($subject);
$description = mysql_real_escape_string($description);
$dbhost = ''; //These are filled in actually
$dbuser = ''; //These are filled in actually
$dbpass = ''; //These are filled in actually
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO organiser '.
'(subject,description) '.
'VALUES ('$subject', '$description')';
mysql_select_db(''); //These are filled in actually
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
The problem is that the input from the Subject and Description boxes on the HTML form don't go into the MySQL Database.
However, If I set
'VALUES ('$subject', '$description')';
to
'VALUES ("test", "test")';
it works.
Any help is appreciated!
Thanks!
In addition to the answer already given in regards to missing dots for the concatenate:
Form method defaults to a GET method, if the method is omitted from the form tag.
You are using <form action="insert.php"> which is equivalent to doing
<form action="insert.php" method = "get"> which is not what you want nor required.
Change it to
<form action="insert.php" method="post">
since you are using POST variables.
That is the contributing reason why 'VALUES ("test", "test")'; works and not the other way, since both of these variables $subject - $description, are based on your POST variables:
$subject = $_POST['subj'];
$description = $_POST['desc'];
You can either do
$sql = "INSERT INTO organiser (subject,description) VALUES ('$subject', '$description')";
as stated in a comment.
or
$sql = "INSERT INTO organiser (subject,description) VALUES ('".$subject."', '".$description."')";
Add error reporting to the top of your file(s)
error_reporting(E_ALL);
ini_set('display_errors', 1);
which would have signaled errors found in your code.
http://php.net/manual/en/function.error-reporting.php
Yet, your method is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
Use a mysqli prepared statements method; it's safer.
<?php
$DB_HOST = "xxx"; // replace with your own
$DB_NAME = "xxx";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
}
// optional to check for empty fields
// if(isset($_POST['submit']) && !empty($_POST['subj']) && !empty($_POST['desc'])) {
if(isset($_POST['submit'])) {
$subject = stripslashes($_POST['subj']);
$description = stripslashes($_POST['desc']);
$stmt = $conn->prepare("INSERT INTO organiser (`subject`, `description`) VALUES (?, ?)");
$stmt->bind_param('ss', $subject, $description);
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
else{
echo "<h2>Success!</h2>";
}
$stmt->close(); // Statement
$conn->close(); // MySQLi
}
?>
Form: (new)
<form action = "insert.php" method = "post">
<label for="subj">Subject:</label>
<br>
<input type="text" name="subj">
<br>
<label for="desc">Description:</label>
<br>
<input type="text" name="desc">
<br>
<input type="submit" value="Submit" name="submit">
</form>
Your problem is because you are using single quotes in your $sql declaration,
$sql = 'INSERT INTO organiser '.'(subject,description) '.'VALUES ('$subject', '$description')';
When you use single quotes you are telling PHP that you would like everything within the quotes to be taken literally.
$age = 20;
$myAge = 'I am $age years';
echo $myAge;
This would echo I am $age years since you used single quotes.
However, if you used double quotes instead,
$age = 20;
$myAge = "I am $age years";
echo $myAge;
The output would be,
I am 20 years
Thus, your $sql statement should be (I write it on one line instead),
$sql = "INSERT INTO organiser (subject,description) VALUES ('$subject', '$description')";
^ ^
If you echo your $sql it would become something along the lines of,
INSERT INTO organiser (subject,description) VALUES ('Your subject', 'Your description')
Your use of single quotes within your SQL-statement is correct, you can read more about the subject here: When to use single quotes, double quotes and backticks
You forgot the dots around the variables and you can add some double quotes around that depending on the content of your variables :)
'VALUES ("'.$subject.'", "'.$description.'")';

I cant get the form data to go into database. What am I doing wrong?

CODE UPDATED, STILL NOT WORKING.
I know I´m apparently using mysql function which will be outdated. But for now all I want is for this code to work. I want to know what I´m doing wrong:(
I´m very new to php and databases... I have been struggling to get simple html form data to go into the database table. And I just can´t get it to work:( Can anyone help and see what is wrong with my code? I´ve just done a simple table in the database with the fields ID, FIRSTNAME and SURNAME.
Here is the code:
<?php
//connect to database
$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_pass = '';
$mysql_db = 'test';
if (!mysql_connect ($mysql_host, $mysql_user, $mysql_pass)||!mysql_select_db ($mysql_db) ) {
die(mysql_error());
}
// Code
if (isset($_POST['firstname'])&&
isset($_POST['surname'])) {
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
if (!empty($username)&&!empty($password)) {
$query = "INSERT INTO `test`.`test_tabell`
VALUES ('', '" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
/*$query = "INSERT INTO `test`.`test_tabell` VALUES (``, `.$firstname.`, `.$surname.`)"; */
$query_run = mysql_query($query);
if (!$query_run) echo mysql_error();
}
}
?>
<form action="add.php" method="POST">
Firstname:<br> <input type="text" name="firstname" value="<?php if (isset($firstname)) { echo $firstname; } ?>"><br><br>
Surname:<br> <input type="text" name="surname" value="<?php if (isset($surname)) { echo $surname; } ?>"><br><br>
<input type="submit" value="Submit">
</form>
Thank you!
Don't use mysql specific syntax, It's outdated and it begins to be annoying when you need to do some high level stuff, and you can't switch to sqlite or postgresql.
I recommend using PDO, you can do something like:
// Usage: $db = connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables (I think you forgot to define the name of the database);
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$GLOBALS['db'] = connectToDataBase($host , $databaseName, $user, $pass);
Now you have an instance of a PDO database donnection.
One thing I want to point out is that you're vonurable to sql injections, you want to use prepared statements in your query, like:
$query = "INSERT INTO test(first_name, sur_name) VALUES (:firstname, :surname);";
Where we will execute two variables $firstName and $surName on the query, making them replace the values of :firstName and :surName, let me show you by first creating a simple insertion function:
function insertFunction($db, $query, $firstName, $surName)
{
$statement = $db->prepare($query);
return $statement->execute(array(":firstName" => $firstName, ":surName" => $surName));
}
So It's easy for you to do something like
$firstName = 'Smith';
$surName = 'John';
$db = $GLOBALS['db'];
$success = insertFunction($db, $query, $firstName, $surName);
Now you can check if it was successful or not, by checking whether $success is true or false.
If you want to see more advanced use of PDO (multiple rows etc) then you can check out one of my comments here: Javascript function as php?
(Not the top comment).
I hope this helps. Please comment if anything is odd.
Hard to tell without seeing your schema but try this:
$query = "INSERT INTO `test`.`test_tabell` VALUES ('', '$firstname', '$surname')";
$query_run = mysql_query($query);
You're using backticks instead of apostrophes. Also, you're trying to execute a query before defining what the query is.
Your insert query is wrong and also open to SQL injections. Here's how it should be:
$query = "INSERT INTO `test`.`test_tabell`
VALUES ('', '" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
Notice the changing of all backticks to apostrophe.
Also, you're trying to execute the query before defining it.
EDIT
As per your information related to table definition, you can skip the id field from your table. The INSERT query will become:
$query = "INSERT INTO `test`.`test_tabell` (`FIRSTNAME`, `SURNAME`)
VALUES ('" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
$query_run = mysql_query( $query );
As posted in the comments, you REALLY SHOULD NOT use/learn/practice using any function that starts with "mysql_" since it will NOT work as soon as PHP is updated. These functions are on their way out. Best of luck with learning to use PHP and SQL databases - just make sure you're learning something that will be useful in the future. Make sure to read up on Object Oriented Programming (OOP) in relation to PHP and both the PDO and mysqli_* functions.

Whats does pg_escape_string exactly do?

I'm using the following script which takes the data from a html form and stores in a Postgres DB. There is this pg_escape_string function which stores the value from the form to the php variable. Searching the web throughout, I found that pg_escape_string escapes a string for insertion into the database. I'm not much clear on this. What does it actually escaping? What actually happens when its said that a string is escaped?
<html>
<head></head>
<body>
<?php
if ($_POST['submit']) {
// attempt a connection
$dbh = pg_connect("host=localhost dbname=test user=postgres");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// escape strings in input data
$code = pg_escape_string($_POST['ccode']);
$name = pg_escape_string($_POST['cname']);
// execute query
$sql = "INSERT INTO Countries (CountryID, CountryName) VALUES('$code', '$name')";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Country code: <br> <input type="text" name="ccode" size="2">
<p>
Country name: <br> <input type="text" name="cname">
<p>
<input type="submit" name="submit">
</form>
</body>
</html>
Consider the following code:
$sql = "INSERT INTO airports (name) VALUES ('$name')";
Now suppose that $name is "Chicago O'Hare". When you do the string interpolation, you get this SQL code:
INSERT INTO airports (name) VALUES ('Chicago O'Hare')
which is ill-formed, because the apostrophe is interpreted as a SQL quote mark, and your query will error.
Worse things can happen, too. In fact, SQL injection was ranked #1 Most Dangerous Software Error of 2011 by MITRE.
But you should never be creating SQL queries using string interpolation anyway. Use queries with parameters instead.
$sql = 'INSERT INTO airports (name) VALUES ($1)';
$result = pg_query_params($db, $sql, array("Chicago O'Hare"));
pg_escape_string() prevent sql injection in your code

Categories