adding new mySQL table row with PHP doesn't work - php

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

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

Pushing a comment to my database on localhost

So, I'm trying to push a comment to my database (icposts, below), and I'm not getting any results. I can pull and display the comments I directly insert into the database table fine, but when I try to send a comment from the html form, it doesn't seem to work at all.
<?php
$connect=mysqli_connect("localhost","root","");
$database=mysqli_select_db("icposts");
$username=$_POST['poster'];
$title=$_POST['postTitle'];
$body=$_POST['postText'];
$date=$_POST['currentDate'];
$submit=$_POST['submit'];
if($submit)
{
$query=mysql_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')");
}
?>
Here's the form's html, for reference:
<form name="input" action="comments.php" method="POST">
Username: <input id = "poster" type="text" name="poster"value="Guest" /><br>
Tite: <input id = "postTitle" type="text" name="postTitle" /><br>
Comment: <br> <textarea id = "postText" name = "postText"rows="4" cols="50"></textarea>
<input id = "submit" name = "submit" type="submit" value="Submit" />
<input id = "currentDate" name = "currentDate" type = "hidden" value = "" />
</form>
I've been looking at various examples, and I don't see anything wrong with what I've got there, when I compare it to what other people have posted online.
First, you need to pass connection to $database=mysqli_select_db("icposts");.
Then you're starting to mix MySQL APIs with mysql_query. They just don't intermix.
$database=mysqli_select_db($connect,"icposts");
then you're using the wrong identifiers for your table and columns, being quotes.
Either use ticks, or remove them (quotes) and also pass connection to the query:
$query=mysqli_query($connect,"INSERT INTO `posts` (`id`, `username`, `title`, `body`, `date`)
VALUES ('','$username','$title','$body','$date')");
Also add or die(mysqli_error($connection)) to mysqli_query() to check for DB errors, which is the reason why you are not getting errors; you're not checking for them. Error reporting is another you should look into.
Example:
if (!mysqli_query($connection,"INSERT INTO `posts` (`id`, `username`, `title`, `body`, `date`)
VALUES ('','$username','$title','$body','$date')");
)
{
echo("Error description: " . mysqli_error($connection));
}
else{
echo "Success!";
}
You can also use all 4 parameters instead:
$connect=mysqli_connect("localhost", "root", "", "icposts");
You may also want to replace if($submit) with
if(isset($_POST['submit']))
You can then get rid of $submit=$_POST['submit'];. It's best to use isset().
Nota: You will need to make sure that your currentDate column allows for blank data, otherwise you will need to give it some form of value.
Another note about the "id" column. If it is an auto_increment, you can just omit it from the query.
The database will increase on its own.
Sidenote:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
In the meantime till you get into using prepared statements, change your code using:
$username = stripslashes($_POST['poster']);
$username = mysqli_real_escape_string($connection, $_POST['poster']);
and do the same for all your variables.
Here is a prepared statements primer:
<?php
$link = new mysqli('localhost', 'root', '', 'database');
if ($link->connect_errno) {
throw new Exception($link->connect_error, $link->connect_errno);
}
// Check that the expected value has been provided via a POST request
if (!isset($_POST['input1'])) {
throw new Exception('Missing POST request parameter [input1]');
}
// now prepare an INSERT statement
if (!$stmt = $link->prepare('INSERT INTO `your_table` (`name`) VALUES (?)')) {
throw new Exception($link->error, $link->errno);
}
// bind parameters
$stmt->bind_param('s', $_POST['input1']);
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
$connect=mysqli_connect("localhost","root","");
Should be (the select db can simply be removed)
$connect=mysqli_connect("localhost","root","", "icposts");
And
$query=mysql_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')");
Should be
$query=mysqli_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')", $database);
Please do keep in mind that this is a really bad aprouch, also looking at your query it seems like the id is an auto incremented column. If that's the case, you don't even have to write it in the query itself.
You might wanna look further into Parameterizing queries.
This is a nice post for that.
How can I prevent SQL injection in PHP?

linking and sending form values to mysql database?

My html code:
<form action="send_post.php" method="post">
<input type="submit" value="Login" />
</form>
PHP code:
<?php
$con = mysqli_connect("","","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{
// echo('Connected with Mysql');
}
#mysql_select_db("a", $con);// connect to database db_name
if (isset($_POST['Submit']))
{
$email=$_POST['email'];
$pass=$_POST['pass'];
$sql_query="INSERT INTO formdata (email, pass) VALUES('$email', '$pass')";}
?>
Database name: mysql
Table name: formdata
Why it is not working? in second line I used 'local host' first but I was receiving error so I removed it.
You use the mysqli_ API to connect to your database and then test for errors and try to select a database with the mysql_ API. Pick one and stick to it. (Don't pick mysql_ it is deprecated).
You only run the form handling code if there is a Submit data item in the submitted data. You have no form control with name="Submit" so that will never happen.
Your form handling code expects there to be email and pass data in the submitted data but your form does not have fields with those names.
Constructing an SQL query as a string and storing it in a variable is insufficient to do anything to your database. You have to actually sent it to the database server. That would use mysqli_query with your current approach, but you should switch to prepared statements

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..

php form inserting to mysql

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?

Categories