php form inserting to mysql - php

My php code doesn't seem to be working. Was functioning yesterday but I must have changed something and now it isn't. As far as I can tell it's the if($word) that's causing the problem. The else part functions and it's connecting with the mysql db but that one if statement does nothing.
Here's the php:
<?php
require('connect.php');
$word=$_POST['word'];
$submit=$_POST['submit'];
if($submit){
if($word){
mysql_query("INSERT INTO words (word) VALUES ($word)");
}
else{
echo "Enter a word.";
}
}
?>
and this is the html form:
<form name="form" id="form" method="post" action="index.php">
<p><label>Label</label></p>
<p><input type="text" name="word" id="word" maxlength="16"/></p>
<p><input type="submit" name="submit" id="submit" value="Save"/></p>
</form>

You should immediately stop using this code. It is vulnerable to SQL injection. You need to learn how to bind parameters to prevent this as well as use a non-deprecated API. I would also recommend that you check REQUEST_METHOD rather than if $_POST['word'] is set as it can be empty.
Since you don't have any type of error catch functions, it is difficult to tell what could be the problem. If I had to guess, it's probably because you're missing single quotes around your posted variable:
...INSERT INTO words (word) VALUES ('$word')...
Using parameters:
<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['submit']) ) {
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = mysqli_prepare($link, "INSERT INTO words (word) VALUES (?)");
mysqli_stmt_bind_param($stmt, 's', $_POST['word']);
/* execute prepared statement */
mysqli_stmt_execute($stmt);
printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));
/* close statement and connection */
mysqli_stmt_close($stmt);
/* close connection */
mysqli_close($link);
}
?>
The documentation is a good place to start.

You most likely need to quote your $word value...
INSERT INTO words (word) VALUES ('$word')
As mentioned in the comments...
Why shouldn't I use mysql_* functions in PHP?
And don't forget about input sanitization.
How can I prevent SQL injection in PHP?

Related

Info does not submit into database

We have an assignment for school and I've tried to build the application, however some text that I want to have inserted into a database doesn't get submitted.
I've tried different things, but the page does not show an error either.
This is the code of my insert page
<head>
</head>
<body>
<form action="index.php" method="post">
ID: <input type="text" name="id"><br/>
Server: <input type="text" name="Server"><br/>
Student: <input type="text" name="Student"><br/>
Docent: <input type="text" name="Docent"><br/>
Project: <input type="text" name="Project"><br/>
Startdatum: <input type="text" name="Startdatum"><br/>
Einddatum: <input type="text" name="Einddatum"><br/>
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])) {
$con = mysqli_connect("localhost", "root", "usbw", "serverruimte");
if(!$con) {
die(mysqli_connect_error());
}
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('$_POST[id]','$_POST[Server]','$_POST[Student]','$_POST[Docent]','$_POST[Project]','$_POST[startdatum]','$_POST[einddatum]')";
$result = mysqli_query($con, $sql);
if($result) {
echo "Opslaan voltooid!";
} else {
echo mysqli_error($con);
}
mysqli_close($con);
}
?>
</body>
</html>
Basically, what happens is: https://i.imgur.com/aUOx5yj.mp4
Does anyone know what the problem is and why the inserted data does not show up on the index page? The data does show on the page when I submit it directly into the MYSQL database.
Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough!
When working with MySQLi you should enable automatic error reporting instead of checking for errors manually. Checking for errors manually is a terrible practice, very error prone and should be avoided at all costs. Let MySQLi throw exceptions and do not catch them. See How to get the error message in MySQLi?
When opening MySQLi connection you must specify the correct charset. The recommended one is utf8mb4.
if (isset($_POST['submit'])) {
// Enable automatic error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Create new instance of MySQLi class
$con = new mysqli("localhost", "root", "usbw", "serverruimte");
// Set correct charset. Important!
$con->set_charset('utf8mb4');
$stmt = $con->prepare('INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES (?,?,?,?,?,?,?)');
$stmt->bind_param('sssssss', $_POST['id'], $_POST['Server'], $_POST['Student'], $_POST['Docent'], $_POST['Project'], $_POST['startdatum'], $_POST['einddatum']);
$stmt->execute();
echo "Opslaan voltooid!";
mysqli_close($con);
}
Change this line:
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('$_POST[id]','$_POST[Server]','$_POST[Student]','$_POST[Docent]','$_POST[Project]','$_POST[startdatum]','$_POST[einddatum]')";
to:
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('".$_POST['id']."','".$_POST['Server']."','".$_POST[Student]."','".$_POST['Docent']."','".$_POST['Project']."','".$_POST['Startdatum']."','".$_POST['Einddatum']."')";
Reason behind this change is because your query is wrong for the following reasons:
You were using strings instead of concatenating your real values coming from $_POST
Some of your indexes in $_POST were misspelled. For example:
$_POST[einddatum] should be $_POST['Einddatum']
Also, consider that this code is vulnerable to SQL Injection

$_REQUEST doesn't work

I have code
<form action="insert1.php" form method="POST">
<input type="text" name="product" /></p>
<input type="submit" value="Add">
And
$mysqli = configuration();
$product = $_REQUEST['$product'];
$sql = "INSERT INTO Odiet (product) VALUES ('$product')";
if($mysqli ->query($sql)===TRUE){echo "ok";}
else{echo "not ok";}
$mysqli ->close();
It adds empty string without text.
Please help.
Thanks.
Replace this string:
$product = $_REQUEST['$product'];
With this
$product = $_REQUEST['product'];
You should know which one to use, $_REQUEST opens up a huge security risk to your database. Also use preprared statements.
$sql = "INSERT INTO Odiet (product) VALUES (?)";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("s", $_POST['product']);
if($stmt->execute()){
echo "ok";
} else {
echo "not ok";
}
}
There is also little use in closing the db connection as this is automatically done after script execution.
I just fix one error in you code and you need to put it like this:
$mysqli = configuration();
$product = $_REQUEST['product'];
$sql = "INSERT INTO Odiet (product) VALUES ('$product')";
if($mysqli ->query($sql)===TRUE){echo "ok";}
else{echo "not ok";}
$mysqli ->close();
You get values from html form by field name, but without dolar sign before.
And be aware that your code is not safe. Don't put raw user data in your sql statement, use prepared statements instead

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}')";

Why use quote and dot before $_POST in insert query?

For example I have a html file like below:
<html>
<form action="insert.php" method="post">
Name:<input type="text" name="txtname" />
<input type="submit" name="but" value="Submit" />
</form>
</html>
and a php file like below:
<?php
if(isset($_POST['but']))
{
mysqli_query($con,"insert into student(Name) values(".$_POST["txtname"].")");
}
?>
My question is that if I can write $name=$post['txtname'] and I use $name in values part then dot
is not used but if I write directly post in values part then dot is used, why this dot used?
You have two possibilitys to do this...
First:
mysqli_query($con,"insert into student(Name) values(" . $_POST['txtname'] . ")");
// using single quotes instead of double quotes
Second
mysqli_query($con,"insert into student(Name) values({$_POST['txtname']})");
//dont use any dots but single quotes and simply add it to the string
Also you should care about some singlequotes to the content...
"... values('{$_POST['txtname']}')"
so it should be
mysqli_query($con,"insert into student(Name) values('{$_POST['txtname']}')");
and as in the comments pointed... you have injection problems and consider to solve this.
Your PHP
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'foobar');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO students ( Name ) VALUES ( ? )");
$stmt->bind_param('s', $_POST['txtname']);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
?>
You can use $name with and without dots, but $_POST['something'] is different in the way that the index has quotes. It will break your query.
It is not related to $_POST it is related to arrays
You could also write it like
mysqli_query($con,"insert into student(Name) values('{$_POST['txtname']}')");
On another note, you should not insert form input directly into the database.
Do some validation first.

Database cannot create a record when a text value is entered ($_POST)

Perhaps I'm making some obvious beginner mistake, but I just cannot seem to figure out why this happens.
Strangely enough, the code only seems to work properly if I enter a number into the "inputbox". I check this in the myphpadmin panel, and it shows a new record has been created. However, if I attempt to input a string as intended for my purposes (example: "hello") no new record appears in the database...
In short, the database only updates if I put a number into the "inputbox" but not when I enter a string.
Any ideas why this may be happening? It's driving me crazy. If it helps, the data type of the "Company" field is VARCHAR and the collation is set to latin1_swedish_ci
The PHP code is as follows:
<?php
//Retrieve data from 'inputbox' textbox
if (isset($_POST['submitbutton']))
{
$comprating = $_POST['inputbox'];
//Create connection
$con = mysqli_connect("localhost","root","","test_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Insert data into 'Ratings' table
mysqli_query($con,"INSERT INTO Ratings (Company,Score)
VALUES ($comprating,1)");
mysqli_close($con);
}
?>
The HTML code is:
<form method="post">
<input type="text" name="inputbox">
<input type="submit" name="submitbutton">
</form>
Cheers
Try this query,
mysqli_query($con,"INSERT INTO Ratings (Company,Score)
VALUES ('$comprating',1)");`
^ ^
Note the single quotes that reserves the string value and don't forget to sanitize the input before inserting them to database.
Sample standard escaping:
$comprating = mysqli_real_escape_string($comprating) before executing a query that uses $comprating
Hi here is the objected oriented method and also its secure because data binding is used in mysqli. I recommend to use this.
if (isset($_POST['submitbutton'])) {
$comprating = $_POST['inputbox'];
$mysqli = new mysqli("localhost", "root", "", "test_db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO Ratings (Company,Score) VALUES (?, ?)");
$stmt->bind_param($comprating, 1);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$mysqli->close();
}
feel free to ask any questions if you have..

Categories