why data is not inserting to database? - php

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

Related

Insert database not working

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

php mysql login system issues

I think i am missing a small detail but I can't quite figure out what. my database is connected 100% sure of that. my register.php page loads data perfectly. when I try to set the login system I get the same echo "invalid email or password" wether I type good information or bad(just to check). at a certain point.
I changed the code to see if i could post data from my database to my page and it worked perfectly so I guess my PDO connection to the db is good. so why do I always have the same echo for both situations?
<?php
if (isset($_POST['submit'])){
$db_server = "localhost";
$db_user = "root";
$db_password = "";
$db_name = "newsite";
try{
$conn = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
if (!empty($_POST['email']) && !empty($_POST['password'])){
$req = $conn->prepare('SELECT id,email, password FROM users_tb WHERE email= :email');
$req->bindParam(':email',$_POST['email']);
$req->execute();
$result= $req->fetch(PDO::FETCH_ASSOC);
if (count($result)>0 && password_verify($_POST['password'], $result['password'])){
echo "Alleluia!";
}else{
echo "invalid email or password";
}
}
}
?>
the for
<body>
<form method="POST" action="login.php">
<table width="400" border="5" align="center">
<tr>
<td colspan="5">Login</td>
</tr>
<tr>
<td align="center">Email</td>
<td><input type="text" name="email"></input></td>
</tr>
</tr>
<tr>
<td align="center">Password</td>
<td><input type="password" name="password"></input></td>
</tr>
</tr>
<tr>
<td><input type="submit" name="submit" value="sign up"></input></td>
</tr>
</table>
</form>
</body>
The issue is that you are using password_verify which verifies that a password matches a hash.
Looking at your comments though you are not storing a hash, you are storing the actual password 0987654.
So, when entering the password into the database you must save the result of
password_hash("your_password", PASSWORD_DEFAULT) where your_password is your password, rather than just storing the value such as 0987654
Your hash should be 60 characters by default, it should look something like...
$2a$04$PnJr5Vo/EDwbCV0z16ceyuj.z4Cw..6L/0cfFPgTCPv0un0qBp.qm

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.

Adding data to SQL not working

I am currently learning SQL and have created this code for a few hours but I am unable to add data to my SQL server. Below I have provided a minimum working example of an input field and submit to SQL server. Any help is greatly appreciated. (I removed the password). I believe the problem is with isset($_POST['submit'] or before this point as the server does not seem to acknowledge the rest.
With thanks!
<html>
<body>
<table class="dd" width="100%" id="data">
<td>Field</td>
<td>:</td>
<td width="17%"><input type='textarea' name='field'/></td>
</table>
<input name='submit' type='submit' value='submit'/>
<?php
// Setting up the Database Connection
$username = "root";
$password = "";
$dbname = "table_name";
$link = mysqli_connect('localhost', $username, $password);
#mysqli_select_db($dbname);
if(isset($_POST['submit']))
{
$field = isset ($_POST['field']);
$field_f = mysql_real_escape_string($field);
$que = "INSERT INTO table_test ('fieldsql') VALUES ('$field_f')";
mysqli_query($que);
if (mysqli_query($link,$que) === TRUE) {
echo "Record added successfully";
}}
mysqli_close($link);
?>
</body>
</html>
You are missing form in your html. Without form tag your textarea and submit button wont work.
Try this :
<html>
<body>
<form method="post">
<table class="dd" width="100%" id="data">
<td>Field</td>
<td>:</td>
<td width="17%"><input type='textarea' name='field'/></td>
</table>
<input name='submit' type='submit' value='submit'/>
</form>
Also your query is wrong. Please use following query :
"INSERT INTO table_test (fieldsql) VALUES ('$field_f')";
Side note : Your query is unsafe. Read this
How can I prevent SQL injection in PHP?.

Cant get data from a form to my mysql database

I have problem to get my code working in php
I want to move data from a form in html to my mysql database but it dont work??
Form part
<form action ="Mydbsinsertpersson4.php" method='POST'>
<table>
<tr><td width='100'>För namn:<input type='text' name='fnamn'><td></tr>
<tr><td width='100'>Efternamn:<input type='text' name='enamn'><td></tr>
</table>
<tr><td><input type='submit' name='Submit' value='Submit'><td></tr>
</form>
the php part
<?php
if(isset($_POST["submit"])){
require_once 'Mydbconfig.php';
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO tpersson (Perfnamn, Perenamn)
VALUES ('".$_POST["fnamn"]."','".$_POST["enamn"]."')";
$conn = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
the connection to my mysql database works i can get data from the database but not input to it.
Thanks in the advanced.
This is on of many solutions i have tried non have worked!!
The problem is :-
<tr><td><input type='submit' name='Submit' value='Submit'><td></tr>
And you write:-
if(isset($_POST["submit"])){
Note:- either change name = submit in first one or change $_POST["Submit"] in second one. Thanks.
I like to do this using two files, one for handling the inputs and one for the actual form.
form.html:
<form action ="/assets/post_people.php" method='POST'>
<table>
<tr><td width='100'>Firstname:<input type='text' name='fname'><td></tr>
<tr><td width='100'>Lastname:<input type='text' name='lname'><td></tr>
</table>
<tr><td><input type='submit' name='Submit' value='Submit'><td></tr>
</form>
Now, for post_people.php:
<?php
//db
require_once 'db_connect.php';
//Get and filter input # to avoid injections
$Firstname = mysql_real_escape_string($_POST['fname']);
$Lastname = mysql_real_escape_string($_POST['lname']);
//Check if the user has submitted the form
if(isset($_POST['Submit'])){
//Check if the person already exist in our database
$Check_people = mysql_query("SELECT * FROM People WHERE Firstname = '$Firstname' AND Lastname = '$Lastname'");
if(mysql_num_rows($Check_people)==1){
//The person already exists with exact same data!
}
//The person did not exist in our database, so we'll update.
else{
$update_query = mysql_query("INSERT INTO People (Firstname, Lastname) VALUES ('$Firstname', '$Lastname')");
if($update_query){
//success
}
else {
//Error
}
}
mysql_close();
}
//The user didnt submit the form and tried to access the file ?
//Redirect to /form.html & kill the script.
else{
header("Location: /form.html");
die;
}
I don't know if this will work for you, but it did work for me :)
(Yes im well aware that you shouldn't use mysql_ functions as they are depreciated but they are still working and are easy to use :))
Errors
Incorrect in submit tag name name='Submit'
improve your HTML codeing format(</table> tag should close after last </tr> tag)
Avoid SQL Injections by using mysql_real_escape_string()
So your final code would be
<form action ="Mydbsinsertpersson4.php" method='post'>
<table>
<tr><td width='100'>För namn:<input type='text' name='fnamn'><td></tr>
<tr><td width='100'>Efternamn:<input type='text' name='enamn'><td></tr>
<tr><td><input type='submit' name='submit' value='Submit'><td></tr>
</table>
</form>
In Mydbsinsertpersson4.php
<?php
if(isset($_POST["submit"])){
require_once 'Mydbconfig.php';
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$fname = $mysqli->real_escape_string($_POST["fnamn"]);
$ename = $mysqli->real_escape_string($_POST["enamn"]);
$sql = "INSERT INTO tpersson (Perfnamn, Perenamn) VALUES ('$fname','$ename')";
$conn = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>

Categories