Insert database not working - php

Hi Im working on a school project and i cant insert this into the database
What am I doring wrong? I dont have any error`s so I im stuck. Please help me. I do have a connection to the database. But the things I insert into the form do not show in to the databse.
$servername = "localhost";
$username = "root";
$password = "root123";
$dbname = "ToetsPro";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "INSERT INTO `opleiding` (`id`,
`opleiding`,
`locatie`)
VALUES (NULL,
'".$_POST["opleiding"]."',
'".$_POST["locatie"]."');";
//echo $query; exit();
$result = mysqli_query($conn, $query);
$id = mysqli_insert_id($conn);
?>
<!DOCTYPE HTML>
<form id="register" action="" method="post">
<table>
<tr>
<td>Opleiding: </td>
<td><input type="text" name="opleiding"></td>
</tr>
<tr>
<td>Locatie: </td>
<td><input type="text" name="locatie"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit"></td>
</tr>
</table>
</form>
Terug naar de homepage

What am I doring wrong? I dont have any error`s so I im stuck.
well there are few things you doing wrong.
one of the very first things I have noticed is that you are mixing up Object oriented style and Procedural style
doing so might confuse you in the long run.
here your db connection
$conn = new mysqli($servername, $username, $password, $dbname);
You using mysqli object oriented style
Then here : $result = mysqli_query($conn, $query); You using procedural style. I suggest that you only stick with one style, in that way you can easily read,organize and maintain your code.
two : You might be making an error with your insert statement, id then inserting a null on the ID that might be the problem, if your id is an auto_increment better not even include it within your query.
three You are writing a dangerous code, that will harm your application in the long run. you are directly inject $_POST values in your query, that might dangerous and it leave your application wide open to sql injections
You should learn to use prepared statements, with mysqli or PDO prepared statements.
This is how your code should look :
<?php
$servername = "localhost";
$username = "root";
$password = "root123";
$dbname = "ToetsPro";
// 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'])) {
//check and validate your inputs
$opleiding = $_POST['opleiding'];
$locatie = $_POST['locatie'];
$query = $conn->prepare("INSERT INTO `opleiding` (opleiding,locatie)VALUES(?,?)");
$query->bind_param("ss", $opleiding, $locatie);
if ($query->execute()) {
echo "success";
$id->insert_id;
} else {
echo "Error :" . $conn->error;
}
}
?>
<!DOCTYPE HTML>
<form id="register" action="" method="post">
<table>
<tr>
<td>Opleiding: </td>
<td><input type="text" name="opleiding"></td>
</tr>
<tr>
<td>Locatie: </td>
<td><input type="text" name="locatie"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit"></td>
</tr>
</table>
</form>
Terug naar de homepage

I think first of all you should use mysqli_real_escape_string() for every variable data filtering then your query should like this way:
$query = "INSERT INTO `opleiding` (`id`,`opleiding`,`locatie`) VALUES (NULL,'".$_POST['opleiding']."','".$_POST['locatie']."')";

Related

MYSQL insert into database using php and html form

I'm trying to insert into an MYSQL database using php and an html form. When I press submit it says an item inserted successfully but when I log into phpmyadmin the table is empty?
My html form code is creon.html.
<form name="bmr_calc" action="https://cs1.ucc.ie/~lmm12/Project/creon.php" method="POST" id="BMRform">
<h1 id="info">Creon Calculator</h1>
<table>
<tr>
<td colspan="2" align="center">I take one: <br>
<input type="radio" name="creon1" value="10" required> Creon 10,000
<input type="radio" name="creon1" value="25" required> Creon 25,000
<br>per <input type="text" name="creon3" required>g of fat
</td>
</tr>
<br>
<tr>
<td>There are:</td>
<td><input type="text" name="creon4" required>g of fat in the item I'm about to eat</td>
</tr>
</table>
<td><input type="submit" value="Submit" style="float:center">
<br>
<img src="img/regpic.jpg" alt="reg" id="reg">
<br>
</td>
</form>
My php code is creon.php and it's saved on my college server;
<?php
$creon1 = $_POST['creon1'];
$creon3 = $_POST['creon3'];
$creon4 = $_POST['creon4'];
if (!empty($creon1) || !empty($creon3) || !empty($creon4)) {
$host = "cs1.ucc.ie";
$dbUsername = "lmm12";
$dbPassword = "----";
$dbname = "mscim2018_lmm12";
//create connection
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
} else {
$INSERT = "INSERT Into creon (creon1, creon3, creon4) values(?, ?, ?)";
//Prepare statement
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("sss", $creon1, $creon3, $creon4);
$stmt->execute();
echo "New record inserted sucessfully";
$stmt->close();
$conn->close();
}
} else {
echo "All field are required";
die();
}
This seems to be either a type issue in MySQL or a Type issue in your PHP code
To be sure, upload your data types from the table creon aka are the fields varchars, text etc.
Notice the if/else statement around bind_param you need to do that too just in case something isn't quite right, also capitalize INTO in your statement.
I ran the following:
<?php
$creon1 = $_POST['creon1'];
$creon3 = $_POST['creon3'];
$creon4 = $_POST['creon4'];
if (!empty($creon1) || !empty($creon3) || !empty($creon4)) {
$host = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbname = "quick";
//create connection
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
} else {
$test = "INSERT INTO testing (creon1, creon3, creon4) values(?, ?, ?)";
//Prepare statement
$stmt = $conn->prepare($test);
if ($stmt != false)
$stmt->bind_param("sss", $creon1, $creon3, $creon4);
else
print("Returns false");
$stmt->execute();
echo "New record inserted sucessfully";
$stmt->close();
$conn->close();
}
} else {
echo "All field are required";
die();
}
?>
It gave me this result after submitting the form:
In my database it inserted the row:

why data is not inserting to database?

i am using php for inserting data in in mysql database. i am new to php and also mysql please help
<html>
<head>
<title>create menu</title>
</head>
<h1 align="center">create menu</h1>
<h2 align="center">Dont create more than 7 menu</h2><br/><br/>
<form method="post">
<table border="2px" width="500px">
<tr>
<th colspan="2" align="center">create menu</th>
</tr>
<tr>
<td align="right">menu name</td>
<td><input type="text" name="menu"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="create"></td>
</tr>
</table>
</form>
<?php
mysql_connect("localhost","root","");
mysql_select_db("coupons");
if(isset($_POST['submit'])){
$menu=$_POST['menu'];
$query = "insert into menu(item) values ('$menu')";
if(mysql_query($query)){
echo "<h1 align='center'>DATA INSERTED</h1>";
}
else{
echo "<h1>data not inserted</h1>";
}
}
?>
where am i wrong please help data is not inserting to database
First thing which version of php you are using, because mysql_connect() is not supported in newer version of php.
If your php version doesn't support this function you should get error on submit.
so i suggest you to replace mysql_xxx with mysqli_xxx (as you can see here mysql_connect)
replace these 2 lines
mysql_connect("localhost","root","");
mysql_select_db("coupons");
with these lines of code
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"coupons");
And
update if condition with this mysqli_xxx() as
if(mysqli_query($query))
For more detail please read mysqli_connect
you can do like this, for your php code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "coupons";
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query=$conn->prepare("INSERT INTO menu( item) VALUES( :menu)");
$query->bindParam(':menu',$menu);
$menu=$_POST['menu'];
$query->execute();
echo "<h1 align='center'>DATA INSERTED</h1>";
}
catch(PDOException $e)
{
// roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
echo "<h1>data not inserted</h1>";
}
$conn = null;
?>
Your code is working absolutely fine. I tried it on my system. Check the screenshot -
HTML form submission result -
Value in database -
Possible errors on your system -
MySql is not running.
Database name is incorrect
You have not provided the password

Registration form doesn't send data to database

So I made this registration form but it won't send the data to my database, it works sometimes and sometimes it doesn't, it is really weird. here is the code.
<?php
error_reporting(E_ALL);
define('DB_HOST', 'localhost');
define('DB_NAME', 'Users');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db('Users', $con) or die("Failed to connect to MySQL: " . mysql_error());
function NewUser()
{
$firstname = $_POST['firstname'];
$efternamn = $_POST['efternamn'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO WebsiteUsers (firstname,efternamn,email,password) VALUES ('$firstname','$efternamn','$email','$password')";
$data = mysql_query($query) or die(mysql_error());
if ($data) {
echo "YOUR REGISTRATIOfafa";
}
}
function SignUp()
{
if (!empty($_POST['email'])) {
$query = mysql_query("SELECT * FROM Websiteusers WHERE email = '$_POST[email]' ") or die(mysql_error());
if (!$row = mysql_fetch_array($query) or die(mysql_error())) {
NewUser();
} else {
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
}
}
if (isset($_POST['submit'])) {
SignUp();
}
<!DOCTYPE HTML>
<html>
<head>
<title>Registrera Dig</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table style=" position:absolute; left:550; top:200;">
<form method="POST" action="signup.php">
<tr> <p style=" position:absolute; left:555; top:163;" >Namn</p><td> <input type="text" name="firstname"></td>
</tr>
<tr> <td>Efternamn</td><td> <input type="text" name="efternamn"></td> </tr>
<tr> <td>Email</td><td> <input type="text" name="email"></td></tr>
<tr> <td>Lösenord</td><td> <input type="password" name="password"></td> </tr>
<tr> <td>Bekräfta lösenord </td>
<td><input type="password" name="cpass"></td> </tr>
<tr> <td><input id="button" type="submit" name="submit" value="Skapa konto"></td> </tr>
</form>
</table>
</body>
</html>
What am I doing wrong here?
Update
So everytime I empty my table I am able to register again. but I can only register 1 time
Your code has so many problems, I just re-created it for you using best practices. Where you went wrong was the following:
1.Using MySQL (A depreciated class)
2.Vulnerable to SQL injection
3.You don't need functions, it's just as clean if you don't have them. You're only calling the code once.
4.Inserting $_POST[email] is not a good idea and probably won't work.
5.Fixed multiple other problems such as tags
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'Users');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); //Use MySQLi as MySQL is depreciated.
if (isset($_POST['submit'])) {
//No need for functions, do it all here as otherwise you'll have to declare globals.
if (!empty($_POST['email'])) {
$query = mysqli_prepare($con, "SELECT * FROM Websiteusers WHERE email = ?"); //Preparing the SQL query (We don't insert values directly into the query)
mysqli_stmt_bind_param($query, "s", $_POST['email']); //Bind the email to the SQL query
mysqli_stmt_execute($query); //Execute the query
mysqli_stmt_store_result($query); //Store the results
if(mysqli_stmt_num_rows($query) != 0) //Is the number of rows 0?
{
//rows
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
else
{
//No Rows
$query = mysqli_prepare($con, "INSERT INTO WebsiteUsers (firstname,efternamn,email,password) VALUES (?, ?, ?, ?)"); //Preparing the SQL query (We don't insert values directly into the query)
mysqli_stmt_bind_param($query, "ssss", $_POST['firstname'], $_POST['efternamn'], $_POST['email'], $_POST['password']); //Bind the params to the SQL query
mysqli_stmt_execute($query); //Execute the query
echo "YOUR REGISTRATIOfafa";
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Registrera Dig</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table style=" position:absolute; left:550; top:200;">
<form method="POST" action="signup.php">
<tr> <p style=" position:absolute; left:555; top:163;" >Namn</p><td> <input type="text" name="firstname"></td> </tr>
<tr> <td>Efternamn</td><td> <input type="text" name="efternamn"></td> </tr>
<tr> <td>Email</td><td> <input type="text" name="email"></td></tr>
<tr> <td>Lösenord</td><td> <input type="password" name="password"></td> </tr>
<tr> <td>Bekräfta lösenord </td>
<td><input type="password" name="cpass"></td> </tr>
<tr> <td><input id="button" type="submit" name="submit" value="Skapa konto"></td> </tr>
</form>
</table>
</body>
</html>
i would simplify your code and remove conditions. Shorter code will make it easier to debug and then check line by line what's happening.
A blank screen is weird unless it's something to do with the way you've set up error handling? Do u get any other warnings of something basic goes wrong? To test maybe you should try writing a line of code that definitely gets an error such as including a file that doesn't exist? Do you then get an error ? If not, it's something to do with the way you've configured your error reporting ... This doesn't solve the problem, but will bring you a step closer as when u actually get the error displayed you'll find out why the DB is not registering your form data.

Input data does not get stored in database, but no error

I need to get a user's comment and store in the database table column 1 and display the entered comment in different table. The code works fine with no errors, but the comment does not get stored in the database.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method='post' action=''>
<input type="text" name='Comment'/>
<input type="Submit" value="Submit" name="Submit" />
</form>
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "escalation";
$conn = new mysqli($server, $username, $password, $database);
if ($conn->connect_error) {
die("connection failed:" . $conn->connect_error);
}
if (isset($_POST['Submit'])) $Comment = isset($_POST['Comment']) ? $_POST['Comment'] : '';
$sql = "INSERT INTO css(Dis_Cmt)VALUES('$Comment')";
$res = $conn->query($sql);
if ($res) {
echo "Successful";
echo "<br />";
echo "<a href='Uploadphp.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>
</body>
</html>
try this.Notice the opening and closing bracket.
<head>
<title></title>
</head>
<body>
<form method='post' action=''>
<input type="text" name='Comment'/>
<input type="Submit" value="Submit" name="Submit" />
</form>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "escalation";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['Submit'])){
$Comment=isset($_POST['Comment']) ?$_POST['Comment']:'';
$sql="INSERT INTO css(Dis_Cmt)VALUES('$Comment')";
$res=$conn->query($sql);
if($res){
echo "Successful";
echo "<BR>";
echo "<a href='Uploadphp.php'>Back to main page</a>";
}else {
echo "ERROR";
}
}
?>
</body>
</html>
Another info and a sort of advice though it does not concern to your question is please use prepared statement that will help prevent sql injection.
You can read php manual about mysqli prepared statement here .
You might also want to check PDO prepared statement click here.
You might also want to check this this full helper class for your crud operation that i personally created.That also uses PDO prepared statement.
Hope that helps somebody.
Try this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method='post' action=''>
<input type="text" name='Comment'/>
<input type="Submit" value="Submit" name="Submit" />
</form>
<?php
$server="localhost";
$username="root";
$password="";
$database="escalation";
$conn = new mysqli($server, $username, $password, $database);
if ($conn->connect_error) {
die("connection failed:" . $conn->connect_error);
}
if(isset($_POST['Submit'])){
$Comment=isset($_POST['Comment']) ?$_POST['Comment']:'';
$sql="INSERT INTO css(Dis_Cmt)VALUES('$Comment')";
$res=$conn->query($sql);
if($res){
echo "Successful";
echo "<BR>";
echo "<a href='Uploadphp.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
}
?>
</body>
</html>
Did you check if the $_POST is giving the output you want. If yes ,then try the mysql command on the commandline and see if it shows any error ... Your command should work, i tried it in my commandline, it worked.
Either you havent set the correct data types and lengths of values in the database table or try this:
A safe command which always works is
"INSERT INTO `css`(`Dis_Cmt`)VALUES('.$Comment.')"
First thing I notice:
if ($conn->connect_error) {
die("connection failed:" . $conn->connect_error);
}
should be
(!$conn)
Put a echo before the INSERT. If its show up, the problem maybe the
query or the table field;
Insert any value in css table using the
phpmyadmin for testing;
Use prepared statement to avoid sql
injection. Below, a example.
$Comment = $_POST['Comment'];
$sql = "INSERT INTO css (Dis_Cmt) VALUES (?)";
$statement = $conn->prepare($sql);
$statement->bind_param('s', $Comment);
if($statement){
echo "Successful";
echo "<BR>";
echo "<a href='Uploadphp.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
$statement->close();
Good luck!

PHP form not saving information to mySQL database error

Ok, so I have tested if the database is connected and it is. But, my problem is that the form won't go onto the output.php page to be able to save it to the database, I'm getting a NOT FOUND error. I have included a screenshot of the error, the code seems right to me but I can't figure out why it can't find the page when it's clearly in the FOLDER. Thanks for your time in advance.
form.php file
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$fname = $surname = "";
?>
<h2>Fill out user details</h2>
<form action="output.php" method="post" >
First Name: <input id="fname" type="text" name="fname" >
<br><br>
Surname <input id="surname" type="text" name="surname">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
output.php file
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php $fname=$_POST["fname"];
$surname=$_POST["surname"];?>
<!--Connect to the database-->
<?php
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully"; ?>
<?php
$sql="INSERT INTO 'user'.'user_tbl'('user_fname','user_surname') VALUES ('$fname','$surname')";
mysqli($conn,$sql);
?>
<?php
header("Location: http://localhost/mysite/");
?>
</body>
</html>
There are a few things wrong with your code.
You are using the wrong identifiers for your table and columns, being single quotes.
Use bacticks
$sql="INSERT INTO `user`.`user_tbl`(`user_fname`,`user_surname`) VALUES ('$fname','$surname')";
Then there is this line mysqli($conn,$sql); it should be mysqli_query($conn,$sql);
or
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
}
Then this
$conn = new mysqli($servername, $username, $password);
there should be a 4th parameter for it being for the database
$conn = new mysqli($servername, $username, $password, $database);
however, I see no variables set for any of these.
Here is an example taken from http://php.net/manual/en/function.mysqli-connect.php
$link = mysqli_connect("myhost","myuser","mypassw","mybd")
or die("Error " . mysqli_error($link));
or using your variables and the one that was missing, and replacing with your own credentials
$servername = "localhost"; // or what your service provider said to use
$username = "username"; // your username
$password = "password"; // if one is needed. Leave blank if no password is needed
$database = "your_database"; // your database name
$conn = new mysqli($servername, $username, $password, $database);
Plus, your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Checking for errors would have signaled the error, if you had used mysqli_query instead of just mysqli
or die(mysqli_error($conn)) to mysqli_query()
However, you are doing what is called "outputting before header" with HTML above your PHP
the header being
header("Location: http://localhost/mysite/");
you need to place your HTML under PHP.
Actually, you don't need the following tags for your SQL/PHP
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
and
</body>
</html>
Just the PHP/SQL.

Categories