query not sending to database - php

Embarrassing question here as it's obviously something so simple that's going wrong.
(Also for anyone who claims 'duplicate', I've spent 3 hours on here looking up relevant questions and putting numerous answers into practice but to no avail, hence the need for the question.)
I'm in the process of making a user registration form using PHP and MySQL, everything submits fine, however, I don't see the values in my database? So obviously it isn't submitting fine.
THE QUESTION
Why isn't it submitting?
I've done a var_dump($_POST); and the result is :
array(4) { ["name"]=> string(14) "Foo Bar" ["email"]=> string(18) "foob#bar.com" ["password"]=> string(8) "foobar123" ["submit"]=> string(8) "Register" }
I've also done print_r($query); on the query to see what's being passed and the result is:
INSERT INTO user_info (name, email, password) VALUES ('Foo Bar', 'foo#bar.com', '$2y$10$36UQIGc6OwFrNs/TBfc6letRlrrdRGGoj.lh65puJElDJER08ozQe')
The table user_info already exists and my connection to the database is fine.
I've tried using backward commas for the column names, I've also tried not using commas for the values but nothing seems to be submitting.
Here's the code:
HTML -
<form method="post" name="register-form" action="database.php">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
Password: <input type="password" name="password">
<input type="submit" name="submit" value="Register" />
</form>
PHP -
<?php
require 'dbconnect.php';
function registerUser() {
$username = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_BCRYPT);
$mysqli = mysqli_init();
$query = "INSERT INTO user_info (name, email, password) VALUES ('$username', '$email', '$hash')";
$mysqli->query($con, $query); //$con referenced in dbconnect to connect to db
var_dump($_POST);
print_r($query);
}
if(isset($_POST['submit']) === TRUE){
registerUser();
}
?>
dbconnect.php
<?php
$dbserver = 'localhost';
$dbusername = 'foo';
$dbpassword = 'bar';
$dbdatabase = 'usersdb';
$con = mysqli_connect($dbserver, $dbusername, $dbpassword, $dbdatabase);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
I'm starting to think this might be permission related but it's on my localhost using XAMPP so surely it can't be? Any help would be greatly appreciated! Thank you.

Inside your function registerUser there is no $con defined.
create a connection and your data will get inserted.
function registerUser($con) {
$username = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_BCRYPT);
$mysqli = mysqli_init();
$query = "INSERT INTO user_info (name, email, password) VALUES ('$username', '$email', '$hash')";
$mysqli->query($con, $query); //$con referenced in dbconnect to connect to db
var_dump($_POST);
print_r($query);
}

The problem lies here:
$mysqli = mysqli_init();
$query = "INSERT INTO user_info (name, email, password) VALUES ('$username', '$email', '$hash')";
$mysqli->query($con, $query); //$con referenced in dbconnect to connect to db
You need to establish a connection using mysqli_real_connect after mysqli_init or use the constructor new mysqli() instead of those two. Also $mysqli->query uses the $mysqli object and takes only one parameter, your query. If you have specified the connection somewhere else, you need to use mysqli_query. See http://php.net/manual/de/mysqli.query.php

This is the solution :
in your dbconnect.php reaplace this line
$con = mysqli_connect($dbserver, $dbusername, $dbpassword, $dbdatabase);
with
$mysqli = new mysqli($dbserver, $dbusername, $dbpassword, $dbdatabase);
and reaplace the content of database.php with this :
require 'dbconnect.php';
$username = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_BCRYPT);
if(isset($_POST['submit']) === TRUE){
// $mysqli = mysqli_init();
$query = "INSERT INTO user_info (name, email, password) VALUES ('$username', '$email', '$hash')";
$mysqli->query($query); //$con referenced in dbconnect to connect to db
var_dump($_POST);
print_r($query);
}
this should work

Related

How do I get the value of the form into a MySQL table? [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
All I want is to get the var1 from the input into my SQL table. It always creates a new ID, so this is working, but it leaves an empty field in row Email. I never worked with SQL before and couldn't find something similar here. I thought the problem could also be in the settings of the table, but couldn't find anything wrong there.
<input name="var1" id="contact-email2" class="contact-input abo-email" type="text" placeholder="Email *" required="required"/>
<form class="newsletter-form" action="newsletter.php" method="POST">
<button class="contact-submit" id="abo-button" type="submit" value="Abonnieren">Absenden
</button>
</form>
<?php
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
// Connection to DBase
$con = new mysqli($host, $user, $password, $dbase) or die("Can't connect");
$var1 = $_POST['var1'];
$sql = "INSERT INTO table (id, Email) VALUES ('?', '_POST[var1]')";
$result = mysqli_query($con, $sql) or die("Not working");
echo 'You are in!' . '<br>';
mysqli_close($con);
is the id a unique id? that's auto-incremented??
if so you should do something like this
<?php
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
$mysqli = new mysqli($host,$user,$password,$dbase);
$email = $_POST['var1'];
// you might want to make sure the string is safe this is escaping any special characters
$statment = $mysqli->prepare("INSERT INTO table (Email) VALUES (?)");
$statment->bind_param("s", $email);
if(isset($_POST['var1'])) {
$statment->execute();
}
$mysqli->close();
$statment->close();
Simple answer
There are a few things wrong here; but the simple answer is that:
$sql = "INSERT INTO table (id, Email) VALUES ('?', '_POST[var1]')";
...should be:
$sql = "INSERT INTO {$table} (id, Email) VALUES ('?', '{$var1}')";
...OR assuming id is set to auto-increment etc. etc.
$sql = "INSERT INTO {$table} (Email) VALUES ('{$var1}')";
More involved answer
You should really take the time to use prepared statements with SQL that has user inputs. At the very least you should escape the strings yourself before using them in a query.
mysqli
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
$mysqli = new mysqli($host, $user, $password, $dbase); // Make connection to DB
if($mysqli->connect_error) {
die("Error: Could not connect to database.");
}
$email = $_POST["var1"]; // User input from form
$sql = "INSERT INTO {$table} (Email) VALUES(?)"; // SQL query using ? as a place holder for our value
$query = $mysqli->prepare($sql); // Prepare the statement
$query->bind_param("s", $email); // Bind $email {s = data type string} to the ? in the SQL
$query->execute(); // Execute the query
PDO
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
try {
$pdo = new pdo( "mysql:host={$host};dbname={$dbase}", $user, $password); // Make connection to DB
}
catch(PDOexception $e){
die("Error: Could not connect to database.");
}
$email = $_POST["var1"]; // User input from form
$sql = "INSERT INTO {$table} (Email) VALUES(?)"; // SQL query using ? as a place holder for our value
$query = $pdo->prepare($sql); // Prepare the statement
$query->execute([$email]); // Execute the query binding `(array)0=>$email` to place holder in SQL

MySQL insert username and password via php error

MySQL is not inserting the correct username and password in the database. The php code is:
<?php
$username = $_POST["email"];
$password = $_POST["password"];
require 'database.php';
$myquery = "INSERT INTO verify (`username`, `password`) VALUES ('$username','$password')";
$query = mysql_query($myquery);
if (!$query) {
echo mysql_error();
die;
}
?>
I checked the database.php, it is absolutely fine. It is showing username and password as pranav even though the values are different.
Thanks in advance.
Try to re-order you code, maybe some vars are overwritting his values:
<?php
require 'database.php';
$username = $_POST["email"];
$password = $_POST["password"];
$myquery = "INSERT INTO verify (`username`, `password`) VALUES ('$username','$password')";
$query = mysql_query($myquery);
if (!$query) {
echo mysql_error();
die;
}
?>
I found out what the error was . It was happening because the database.php was coded like this.
PHP:
<?php
$username="pranav";
$password="pranav";
$host="localhost";
$database="requester";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db ($database, $server);
$table='verify'
?>
The username and password was getting rewritten.
Thanks Grommy

Bootstrap Form to Database

I created a bootstrap form and want to include the data from the form into my database. My problem is that it is not working and I have no idea why. In my opinion everything is correct. I am looking for hours now but I can't find the issue.
You can find my form here: http://schulkantine.ccsolution.at/registration.php
Please do not look at the style, I have to customize it later.
Here is my register.php! Database connection is working.
<?php
// Create connection credentials
$db_host = 'localhost';
$db_name = 'DBNAME';
$db_user = 'DBUSER';
$db_pass = 'DBPASSWORD';
// Create mysqli object
$connect = new mysqli ($db_host, $db_user, $db_pass, $db_name);
// Error Handler
if ($connect->connect_error) {
printf ("Connection failed: %s\n", $connect->connect_error);
exit();
}
?>
<?php
// Check if form is submitted
if (isset ($_POST['submit'])) {
$anrede = mysqli_real_escape_string ($connect, $_POST['anrede']);
$vorname = mysqli_real_escape_string ($connect, $_POST['vorname']);
$nachname = mysqli_real_escape_string ($connect, $_POST['nachname']);
$strasse = mysqli_real_escape_string ($connect, $_POST['strasse']);
$plz = mysqli_real_escape_string ($connect, $_POST['plz']);
$ort = mysqli_real_escape_string ($connect, $_POST['ort']);
$email = mysqli_real_escape_string ($connect, $_POST['email']);
$telefon = mysqli_real_escape_string ($connect, $_POST['telefon']);
// Validate Input
$query = mysql_query("INSERT INTO user (anrede, firstname_parent, lastname_parent, street_parent, plz_parent, city_parent, email, phonenumber_parent)
VALUES ('$anrede', '$vorname', '$nachname', '$strasse', '$plz', '$ort', '$email', '$telefon')") or die(mysql_error());
}
?>
Hope someone can help me and tell me what my error is!
Try changing
INSERT INTO user (anrede, firstname_parent, lastname_parent, street_parent, plz_parent, city_parent, email, phonenumber_parent) VALUES ('$anrede', '$vorname', '$nachname', '$strasse', '$plz', '$ort', '$email', '$telefon')"
to
INSERT INTO `user` (`anrede`, `firstname_parent`, `lastname_parent`, `street_parent`, `plz_parent`, `city_parent`, `email`, `phonenumber_parent`) VALUES ('$anrede', '$vorname', '$nachname', '$strasse', '$plz', '$ort', '$email', '$telefon')"
Replace this line in your registration.php file. You forget to add "name" attribute so your condition if (isset ($_POST['submit'])) not work.
<button type="submit" name="submit" value="submit" class="btn btn-custom pull-right">Send</button>

Inputted values not saved while inserting data from html form into sql database (html,php,sql)

The problem: insert.php connects fine, but only inserts empty values ('') when I hit 'save' on the html form. The text I type, which I'm trying to insert, isn't saved. Somewhere a connection isn't being made and that data is lost but I can't figure out exactly where. Any help?
HTML insert form (collecting data for 2 parameters, 'user' and 'thread')
<form action="insert.php" method="post">
user: <input type="text" name="user"><br>
thread: <input type="text" name="thread"><br>
<input type="submit" value="Save">
</form>
PHP code to connect to SQL, insert inputted values
<?php
$user = $_POST['user'];
$thread = $_POST['thread'];
$servername = "##.##.###";
$username = "harwoodjp";
$password = "~";
$dbname = "332";
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("SQL (&#9746)<br/> " . $conn->connect_error);
}
echo "SQL (&#9745) <br/>";
$sql = mysql_connect($servername,$username,$password);
mysql_connect($servername,$username,$password);
mysql_select_db("332project");
//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);
echo "<script>window.location='select.php'</script>"; //select.php displays the full table
//close MySQL
mysql_close($sql);
?>
try this
<?php
$user = $_POST['user'];
$thread = $_POST['thread'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
//create connection
$conn = mysql($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("SQL (&#9746)<br/> " . $conn->connect_error);
}
echo "SQL (&#9745) <br/>";
$sql = mysql_connect($servername,$username,$password);
mysql_select_db("db");
//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);
echo "<script>window.location='select.php'</script>"; //select.php displays the full table
//close MySQL
mysql_close($sql);
?>
It might be because the default form posting method is GET.
Either change your $_POST to $_GET or add method="POST" to your form tag.

Is something wrong with this piece of PHP

Can anyone tell me what is the problem with this line of PHP code? I am trying to insert values in a database.
<?php
// Some database detail
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';
$con;
mysqli_query($con,"INSERT INTO members (Name, Password) VALUES ('Daniel', 'abc123')");
// Making connection
$con = mysqli_connect($host, $username, $password, $database) or die(mysqli_error());
?>
THE ERROR:
Notice: Undefined variable: con in C:\xampp\htdocs\database.php on line 13
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\database.php on line 13
Use Following code:
You just need to connect to database before INSERT .
<?php
// Some database detail
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';
$con = mysqli_connect($host,$username,$password,$database) or die("Error " . mysqli_error($con));
mysqli_query($con,"INSERT INTO members (Name, Password) VALUES ('Daniel', 'abc123')");
?>
You are trying to insert a query into the database before making a connection to it. Swith lines 13 and 11.
Check this ..This will help you
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';
$con = mysqli_connect($host, $username, $password) or die(mysqli_error());
$db_selected = mysqli_select_db("mywebsite", $con);
$check= mysqli_query("INSERT INTO members (Name, Password) VALUES ('Daniel', 'abc123')");
if($check)
echo "inserted";
else
echo "not inserted";
webserver reads PHP code line by line from the top of the page.
it displays Undefined variable error on the variable because you use it before you define $con.
so when the webserver reach line 13, it doesn't know what is variable $con and then it throws the error.
My suggestion is the same with the others.
put the
$con = mysqli_connect($host, $username, $password, $database) or die(mysqli_error());
above this
mysqli_query($con,"INSERT INTO members (Name, Password) VALUES ('Daniel', 'abc123')");

Categories