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
Related
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
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}')";
Okay, it was working before.... now all of a sudden it has stopped. i'm not sure why. The only thing i've added was a delete feature.. and after that it no longer submits. I can delete an entry though =D
php code for form
<?php
if (isset($_POST['submit'])){
$con = mysql_connect("localhost", "", "");
if (!$con){
die("Cannot connect:" . mysql_error());
}
$Firstname = $_POST['Firstname'];
$Email = $_POST['Email'];
$Prayer = $_POST['Prayer'];
//if there is no input these messages will come up//
if($Firstname==''){
echo "<script>alert('Please enter your name!')</script>";
exit();
}
if($Email==''){
echo "<script>alert('Please enter your email!')</script>";
exit();
}
if($Prayer==''){
echo "<script>alert('Please enter your prayer request!')</script>";
exit();
}
mysql_select_db("dxh6110",$con);
//if everything is good, information will be submitted to database
$sql = "INSERT INTO ChurchPrayer (Firstname, Email, Prayer) VALUES('$_POST[Firstname]','$_POST[Email]','$_POST[Prayer]')";
if(mysql_query($sql,$con)){
echo "<script>alert('Congratulations, You have successfully submitted your prayer requests. You will hear from us very soon!')</script>";
}
mysql_close($con);
}
?>
Oh, I'm aware that I should be using prepared statements to prevent SQL injection... but I'm not sure exactly what it is or what it looks like. I will definitely add them later, when I get further into my school project. Currently worried about the functionality..
not sure what else needs to be added... i'll add my delete.php
<?php session_start(); //starting the session?>
<?php
//connecting to database
$con = mysql_connect("localhost","","","dxh6110");
//defining variable
$delete_id = $_GET['del'];
//command to remove input from SQL DB
$query = "delete from ChurchPrayer where id='$delete_id'";
if(mysql_query($con,$query)){
echo "<script>window.open('view_prayers.php?deleted=User has been deleted!','_self')</script>";
}
?>
My admin log-in works, and when the admin logs in it brings them to a page which will allow them to view entries and delete entries made to the DB. Currently there are two, but when I try to add more requests.... they don't go to the DB. No errors are given when submit is clicked.
Firstly, ("localhost","xxx","xxx","xxx") doesn't do what you think.
mysql_connect() takes 3 parameters, not 4. The fourth is for something else. Four parameters are what one would use with mysqli_connect(), but those different MySQL APIs do not intermix with each other, so don't use that connection method if you're going to use mysql_ functions.
Consult:
http://php.net/manual/en/function.mysql-connect.php
http://php.net/manual/en/function.mysql-select-db.php
Do as you did in your other question:
$con = mysql_connect("localhost", "xxx", "xxx");
if (!$con){
die("Cannot connect:" . mysql_error());
}
mysql_select_db("your_db",$con);
Then this if(mysql_query($con,$query)){ the connection comes 2nd.
Plus, $_GET['del'] and ?deleted=User inspect that. Those are the two things that stood out for me.
If your delete link is ?deleted=XXX, it needs to be ?del=XXX - XXX being an example.
$_GET['del'] needs to match the parameter in the ?parameter in your method.
I.e.: view_prayers.php?del=XXX if view_prayers.php is the file you're using to delete with.
Plus, as mentioned in comments, this method is insecure.
It's best that you use mysqli with prepared statements, or PDO with prepared statements.
first of all i am pretty new with mysql and php and for now i just want to insert some data in a mysql database form two text box using php.
here the database name is "info" and table name is "students" having three columns like id(primary key, auto increment activated), name and dept. There are two text boxes txtName and txtDept. I want that when i press the enter button the data form the text boxes will be inserted into the mysql database. I have tried the following code but data is not being inserted in the table....
<html>
<form mehtod="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info");
if($_POST){
$name = $_POST['txtName'];
$dept = $_POST['txtDept'];
echo $name;
mysqli_query($con,"INSERT INTO students(name,dept) VALUES($name,$dept);");
}
?>
There are a few things wrong with your posted code.
mehtod="post" it should be method="post" - typo.
Plus, quote your VALUES
VALUES('$name','$dept')
DO use prepared statements, or PDO with prepared statements.
because your present code is open to SQL injection
and add error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
You should also check for DB errors.
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
as well as or die(mysqli_error($con)) to mysqli_query()
Sidenote/suggestion:
If your entire code is inside the same file (which appears to be), consider wrapping your PHP/SQL inside a conditional statement using the submit button named attribute, otherwise, you may get an Undefined index... warning.
Naming your submit button <input type="submit" name="submit" value="Enter"/>
and doing
if(isset($_POST['submit'])){ code to execute }
Just doing if($_POST){ may give unexpected results when error reporting is set.
Rewrite: with some added security using mysqli_real_escape_string() and stripslashes()
<html>
<form method="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" name="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
if(isset($_POST['submit'])){
$name = stripslashes($_POST['txtName']);
$name = mysqli_real_escape_string($con,$_POST['txtName']);
$dept = stripslashes($_POST['txtDept']);
$dept = mysqli_real_escape_string($con,$_POST['txtDept']);
echo $name;
mysqli_query($con,"INSERT INTO `students` (`name`, `dept`) VALUES ('$name','$dept')")
or die(mysqli_error($con));
}
?>
As per the manual: http://php.net/manual/en/mysqli.connect-error.php and if you wish to use the following method where a comment has been given to that effect:
<?php
$link = #mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
?>
God save us all...
Use PDO class instead :). By using PDO you can additionally make prepared statement on client side and use named parameters. More over if you ever have to change your database driver PDO support around 12 different drivers (eighteen different databases!) where MySQLi supports only one driver (MySQL). :(
In term of performance MySQLi is around 2,5% faster however this is not a big difference at all. My choice is PDO anyway :).
I currently have an HTML form with various feilds one for example is :
Please Enter First Name: <input type ="text" name="First_Name" /> <br />
I am trying to get the information from this form into my database. But it does not seem input anything into the database. Code is as follows.
<?php
$dbname='ecig';
$dbhost='localhost';
$dbpass='password';
$dbuser='eciguser';
$dbhandle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("ecig",$dbhandle)
or die("Could not select examples");
$res=mysql_query("INSERT INTO Persons (First_Name, Second_Name) VALUES('$_POST[First_Name]', yes)");
mysql_close();
if (array_key_exists ('check_submit', $_POST ))
echo "Your Name is : {$_POST['First_Name']}<br />";
echo "Your Second Name is : {$_POST['Second_Name']}<br />";
echo "Your Email Address is : {$_POST['Email_Address']}<br />";
echo "Your Password Is : {$_POST['Password']}<br />";
?>
The question is as this is having no impact on my database, is there something i am missing and need to add to my SQL code so that the php and the SQL interact with each other and input the data?
Or am i missing something from the INSERT INTO statement?
Anyway help would be appreciated, Thanks.
There's an error in your query, 'yes' at the end must have quotes.
Try running your query first directly against MySQL to determine if your syntax is correctly, then just replace the values you want.
Should look like this for your example:
$res=mysql_query("INSERT INTO Persons (First_Name, Second_Name) VALUES ('$_POST[First_Name]', 'yes')");
A bit of advice, sanitize your input if you are receiving data from the user, or you will be vulnerable to a SQL injection attack.
And use mysqli_ functions since mysql_ functions are officially deprecated by now. You can read more about those in almost any site, like w3schools.com
Full example of insert with mysqli_ : http://www.w3schools.com/php/php_mysql_insert.asp
Good luck
Use mysql_real_escape_string()
$res=mysql_query("INSERT INTO Persons (First_Name, Second_Name) VALUES ('".mysql_real_escape_string($_POST['First_Name'])."', '".mysql_real_escape_string($_POST[Second_Name])."')");