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 :).
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
Edit: Error: Column count doesn't match value count at row 1
I have been trying for a long time now (hours if not days with multiple attempts) to set up a prepared statement to stop SQL injection attacks and I just cannot get my head around it. Could someone help me out with this and point out where I have went wrong? I want to learn how to do this so I can use it in future but at this rate I will never get it.
The form:
<form action="php/xaddPlayerSkills.php" method="post"> <!--player skills form to be added-->
playerID : <input type="int" name="playerID" value="<?php echo $playerID ?>" readonly> </td></tr>
SquadID: <input type="text" name="squadID"><br>
Passing: <input type="text" name="passing" value="Standard: Spin: Pop:"><br>
Tackling: <input type="text" name="tackling" value="Front: Rear: Side: Scrabble:"><br>
Kicking: <input type="text" name="kicking" value="Drop: Punt: Grubber: Goal:"><br>
Comments: <input type="text" name="comments"><br>
Date: <input type="date" name="date"><br>
<input type="Submit" value = "Add ">
</form>
This is my processing page:
<?php session_start(); include('functions.php');
$sheetNo="";
$playerID=$_POST['playerID'];
$squadID=$_POST['squadID'];
$passing=$_POST['passing'];
$kicking=$_POST['kicking'];
$tackling=$_POST['tackling'];
$comments=$_POST['comments'];
$date=$_POST['date'];
/* Use for error testing - Uncomment to check variable values when executed
ini_set('display_errors', 'On'); ini_set('html_errors', 0); error_reporting(-1);
print_r($_POST); */
//sets up and executes the connection using the information held above
/* THERE IS CONNECTION INFORMATION HERE BUT I HAVE REMOVED IT AS IT IS CREDENTIALS */
$con=mysqli_connect($host,$user,$userpass,$schema);
// Error handling: If connection fails, the next lines of code will error handle the problem and if possible, give a reason why.
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result= mysqli_query($con,"INSERT INTO playerSkills VALUES (playerID,squadID,passing,tackling,kicking,comments,date)");
$insert=$con->prepare($result);
$insert->bind_param("isssssd",$playerID,$squadID,$passing,$tackling,$kicking,$comments,$date);
$insert->execute();
$insert->close();
mysqli_close($con);
header ("location: ../databasePlayers.php");
?>
You have a couple of problems in your code, but the most notable is the placeholders in the query, which should ?'s instead of things like VALUES (playerID,squadID,passing,tackling,kicking... and that you're using a type double, d, to describe a date:
$con=mysqli_connect($host,$user,$userpass,$schema);
// Error handling: If connection fails, the next lines of code will error handle the problem and if possible, give a reason why.
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result= "INSERT INTO playerSkills VALUES (?,?,?,?,?,?,?)";
$insert=$con->prepare($result);
$insert->bind_param("issssss",$playerID,$squadID,$passing,$tackling,$kicking,$comments,$date); // change d to s for the date
$insert->execute();
$insert->close();
Read the docs for clarification on the data types. d is for doubles, not dates. Then look at the examples for what you should use as placeholders.
EDIT: Caution - if one of these columns is an AUTO INCREMENT column you should not include it in the query as the database will take care of making sure the column is updated properly.
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
My form won't save in my db
connect code saved as con_mysql.php:
<?php
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PSWD', '*****');
DEFINE ('DB_NAME', 'lexusdb');
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
?>
form code:
<form method="post" action="newep.php">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>New Content:</legend>
<label>Name: <input type="text" name="newcontent" /></label>
</fieldset>
<br />
<input type="submit" value="add new anime" />
</form>
<?php
echo $newrecord
?>
PHP:
<?php
if (isset($_POST['submit'])) {
include('con_mysql.php');
$nanime = $_POST['newcontent'];
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$newcontent')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('Error inserting new record');
}
$newrecord = "1 anime added";
}
?>
at first it just won't save anything in DB using the form, and now it also have Undefined variable: newrecord
all files saved in the same folder and newep.php is also created. my db consist of table named title, inside title have title_id INT(4) not null auto_increment then title_name VARCHAR(255) not null. I hope you guys can help me with this one as you guys have help me by just searching for what i need THANKS
Edit :
There is few things that your code is missing , but its ok , you still learning and its great way to start , learning from the faults is good .
One of the things and its one of the most important things that you missed is that you have to prevent SQL Injection in your code , even if you code was perfect but you query has that issue then you are in troubles , How can you protect your Query ? by this way : SQL INJECTION
Second , i see you using MYSQLI , which is a good relational database driver, but i prefer you start to use PDO . Whats PDO ?
PDO is an acronym for PHP Data Objects. PDO is a lean, consistent way
to access databases. This means developers can write portable code
much easier. PDO is not an abstraction layer like PearDB. PDO is a
more like a data access layer which uses a unified API (Application
Programming Interface).
Its easy and simple . What's the differenet between PDO and MYSQLI ?
Different between MYSQLI and PDO
Third thing and i will take that from one of the comments by Fred , You need to start using Error reporting , read this :
Errors Reports
Now to the code .
In your code you tried to echo a variable from the form before you receive the data from the form ( before the submit happen ) , so you should first send the data and receive it then do whatever you want with it .
In your code :
<?php
echo $newrecord
?>
The right way as you can see it here :
if (isset($_POST['submit']))
{
include_once('con_mysql.php');
$nanime = $_POST['newcontent'];
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$nanime')";
if (!mysqli_query($dbcon, $sqlinsert))
{
die('Error inserting new record');
}
else
{
$newrecord = "1 anime added";
echo $newrecord;
}
}
I hope that my answer helped you , and remember the first part cause its so important .
Here is the full code .
<html>
<head>
</head>
<body>
<form method="post" action="">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>New Content:</legend>
<label>Name:
<input type="text" name="newcontent" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new anime" />
</form>
<?php
if (isset($_POST['submit']))
{
include_once('con_mysql.php');
$nanime = $_POST['newcontent'];
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$nanime')";
if (!mysqli_query($dbcon, $sqlinsert))
{
die('Error inserting new record');
}
else
{
$newrecord = "1 anime added";
echo $newrecord;
}
}
?>
</body>
</html>
It looks like you have a typo when including the file which opens connection. Instead of:
include('con_mysql.php.php');
I guess it should be:
include('con_mysql.php');
The next thing is checking your $_POST. Only fields with a name would be there, so you need to change your condition from:
if (isset($_POST['submit'])) {
to:
if (!empty($_POST)) {
and finally you are using an uninitialized variable in your query,
so change that line:
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$newcontent')";
to
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$nanime')";
I was checking my webpages for SQL Injection, when the main pages didn't responded to it, I created a test script:
<?
$a = $_POST["a"];
$username="...";
$password="...";
$database="...";
mysql_connect ('...',$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$ress=mysql_query("SELECT username FROM userinfo WHERE id='$a'");
$row = mysql_fetch_array($ress);
print $row[0];
?>
<form name="form" action="hackMe.php" method="POST">
<input id="a" name="a" size="150">
<input name="Submit" type="submit" value="Submit">
</form>
But when I try this line:
'; UPDATE userinfo SET email = 'steve#unixwiz.net' WHERE email = 'testusr#gmail.com
I just get an error, and no change in the database.
Any ideas why?
Quote from the manual:
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified
Highlighting by me. mysql_query() only allows a single query query per call, the second query behind the ; is ignored.
To test SQL injection you have to use a query that doesn't need a second one to do harm.
Edit:
It IS possible to allow multiple queries, but you have to explicitly state this in the mysql_connect() call.
mysql_connect($host, $username, $password, false, 65536);
// defined by MySQL:
// #define CLIENT_MULTI_STATEMENTS 65536 /* Enable/disable multi-stmt support */
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