A HTML form has been created that should (when filled) send the data it's holding to a database inserting a new row so it can be used later on. However, I can't seem to get it to work, I'm getting the following error:
Notice: Use of undefined constant con - assumed 'con' in C:\xampp\htdocs\form\insert.php on line 4
Warning: mysql_query() expects parameter 1 to be string, object given in C:\xampp\htdocs\form\insert.php on line 17
Data not inserted
HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Form linked to database</title>
</head>
<body>
<form action="insert.php" method="post">
Name: <input type="text" name="username">
<br>
Email: <input type="text" name="email">
<br>
<input type="submit" value="insert">
</form>
</body>
</html>
PHP Code
<?php
$con = mysqli_connect('localhost','[retracted]','[retracted]');
if(!con) {
echo 'Not connected to server!';
}
if(!mysqli_select_db($con,'tutorial')) {
echo 'Database not selected!';
}
$Name = $_POST['username'];
$Email = $_POST['email'];
$sql = "INSERT INTO person (Name,Email) VALUES ('$Name','$Email')";
if(!mysql_query($con,$sql)) {
echo 'Data not inserted';
} else {
echo 'Data inserted';
}
//header("refresh:2; url=form.html");
?>
I'm new to PHP and followed the following YouTube tutorial.
I'm also using XAMPP for this, on a localhost. Any help is appreciated. Thank you.
You should change:
if(!con){
echo 'Not connected to server!';
}
to:
if(!$con){
echo 'Not connected to server!';
}
as you're missing a dollar sign there.
Additionally, you're using a mysql_ function here, on the mysqli_ object $con:
if(!mysql_query($con,$sql))
Change this to
if(!mysqli_query($con,$sql))
SQL injection
As your query is vulnerable to SQL injection, then I'd like to recommend you take a look at using prepared statements, or using mysqli_real_escape_string()-- though, this comes with a few gotcha's: https://stackoverflow.com/a/12118602/7374549
You have done two small mistakes ie
1) forgot to add $ before the variable name ie changes is
if(!$con){
echo 'Not connected to server!';
}
2) you are connected with mysqli_connect but you are trying to use mysql_query functions in it. so please change and use mysqli_query
if(!mysqli_query($con,$sql)){ }
This is issue in your case. My suggestion is to use mysqli or PDO that is good practice.
You are not using the correct mySQL query function, you have used:
mysql_query($con
You should use:
mysqli_query
instead. Let me know if you still have issues.
Altough you have a lot of answers right now, I think none of those is the right one. I've written your code new, procedural as you did, but with prepared statements, so you're going to be save to SQL injections.
<?php
$con = mysqli_connect('localhost','[retracted]','[retracted]');
if(!$con){
echo 'Not connected to server!';
}
if(!mysqli_select_db($con,'tutorial')){
echo 'Database not selected!';
}
$Name = $_POST['username'];
$Email = $_POST['email'];
if ($stmt = mysqli_prepare($con, "INSERT INTO person (Name, Email) VALUES (?, ?"))) {
mysqli_stmt_bind_param($stmt, "ss", $Name, $Email);
mysqli_stmt_execute($stmt);
echo "Data inserted";
}
else {
echo "Error";
}
mysqli_close($con);
//header("refresh:2; url=form.html");
?>
I think it should work, if not let me know.
Try this :
<?php
// Create connection
$conn = new mysqli("localhost", "username", "password", "databasename");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('test fname', 'test lname', 'test#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Related
GYZ i dont know why data is not inserting in my data base #Mysql
. infact im using mysqli_connect and mysql_connect both ,I'm still facing same prob ..this is my code:
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$db='school';
#mysqli_connect($servername, $username, $password);
#mysqli_select_db($db); //or die ('not Connect to db ');
if(isset($_GET['submit'])) {
$sid= $_GET['sid'];
$sname= $_GET['sname'];
$fname= $_GET['fname'];
$order= #mysqli_query("insert into school (sid,sname,fname) values ('$sid','$sname','$fname');");
if ($order) {
echo '<br>Input data is successful';
} else {
echo '<br>Input data is not valid';
}
} ?>
I revisited the question and posted the following, seeing that nobody posted one.
You didn't pass the db connection to mysqli_select_db() nor for mysqli_query() and need to assign a variable to the connection first.
Both of those require it in mysqli_ and you may have been accustomed to mysql_ in the past. MySQLi_ is different than MySQL_ when it comes to certain functions that needs a connection.
Sidenote: The # symbol is an error suppressor. Remove it during testing/development.
Another sidenote: Both your database and table bear the same name of school. Make sure that this is correct.
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$db='school';
$connect = mysqli_connect($servername, $username, $password, $db);
if($connect){
echo "Connected";
}
else {
echo "Error: " . mysqli_error($connect);
}
// This isn't needed. You can pass all 4 parameters in one shot.
// $database = mysqli_select_db($connect, $db); //or die ('not Connect to db ');
if(isset($_GET['submit'])) {
$sid= $_GET['sid'];
$sname= $_GET['sname'];
$fname= $_GET['fname'];
$order= mysqli_query($connect, "INSERT INTO school (sid,sname,fname) VALUES ('$sid','$sname','$fname');");
if ($order) {
echo '<br>Input data is successful.';
} else {
// Uncomment the one below once everything is ok.
// echo '<br>Input data is not valid.';
// Comment this below once there are no errors.
echo "There was an error: " . mysqli_error($connect);
}
}
References:
http://php.net/manual/en/function.mysqli-connect.php
http://php.net/manual/en/mysqli.select-db.php
http://php.net/manual/en/mysqli.query.php
Check for errors also via PHP and the query:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
And make sure you're running this off a webserver, or if local that PHP/MySQL are installed, running properly and using http://localhost as opposed to file:///.
Your code is also open to an SQL injection, use a prepared statement.
References:
https://en.wikipedia.org/wiki/SQL_injection
https://en.wikipedia.org/wiki/Prepared_statement
Footnotes:
You seem to want to use this in a table. <form> cannot be child of <table> if you are using those tags outside of the form which wasn't posted in your question; there are stray <td></td> tags.
I have this code and I am using the latest version of XAMPP:
filename: store.html
<!DOCTYPE html>
<html>
<body>
<form action="store.php" method="post">
User input: <input type="text" name="userinput"><br>
<input type="submit">
</form>
</body>
</html>
filename: store.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$input = $_POST["userinput"];
$sql = "INSERT INTO table_1 (s_num)
VALUES ('$input')";
?>
Whatever I do, no data is added to the database. Please help. Thank you.
The problem here is that you never executed the query.
$sql = mysqli_query($conn,"INSERT INTO table_1 (s_num)
VALUES ('$input')");
if(!sql){
echo "Error: " . mysqli_error($conn);
}
else{
echo "Success";
}
Reference:
http://php.net/manual/en/mysqli.query.php
Your present code is open to SQL injection if user-input (other than yourself) ever gets involved.
Use prepared statements, or PDO with prepared statements, they're much safer.
Plus, seeing you are running this from your own machine, make sure you are accessing as http://localhost/file.php as opposed to file:///file.php.
You are not executing your sql insertcode.
After this line:
$sql = "INSERT INTO table_1 (s_num)
VALUES ('$input')";
Add these line:
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
My php has connected to my database however when I try to insert the data, I get the query is not okay response.
if(isset($_POST['Register'])) {
session_start();
$FName = $_POST['First_Name'];
$LName = $_POST['Last_Name'];
$Email = $_POST['Email'];
$PW = $_POST['Password'];
$query = "INSERT INTO user (Fname, Lname, Email, Password) VALUES('{$FName}', '{$LName}', '{$Email}', '{$PW}')";
$result=mysqli_query($con, $query);
if($result){
echo "Query is successfully executed";
}else{
echo "Query is not ok";
}
}
?>
This is my connection code but it tells me that I am successfully connected.
$con = mysqli_connect("localhost", "*******","*******");
mysqli_select_db('batman',$con);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
?>
The database matches all of the inputs and the table name is user so I cannot figure out why it will not insert into the database.
Use error_reporting(E_ALL); at startup
&
use simple $Fname instead {$Fname}
Also check input type="submit" and name=" is name Register"
Maybe you could try to make a class with the script, because I think the problem is the connection that you use , because you are not calling for the connection function when you execute the query.
Regards!
I have just come back to a project that was working fine a month ago. Today I have found im getting a "Warning: mysqli::query(): Couldn't fetch mysqli" error and I have no idea why. I have tried changing the if statement but I still get the same result.
php page
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
error_reporting(E_ALL); ini_set('display_errors', 1);
$email = $_SESSION['email'];
$name = $_SESSION['name'];
$hash = $_SESSION['hash'];
$password = $hash;
echo $name;
echo '<br>';
echo $email;
echo '<br>';
echo $hash;
echo '<br>';
$sql = "INSERT INTO signed_up(`name`, `email`, `password`) VALUES ('$name', '$email', '$password')";
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
//if ($result = $mysqli->query("INSERT INTO `signed_up`(`name`, `email`, `password`) VALUES ('$name', '$email', '$password')")){
//
//header('location: ../register_success.php');
//// $result->close();
//
//}
//else {
// echo "error";
//}
?>
The error im getting
you have succesfuly connected to the database
gptgeoff
up666315#myport.ac.uk
$2y$10$JUi/eSNwbTnM4ZyWetEL6.ELSepLPKLkEiJdi4WYMyp/sEEAk9hKe
Warning: mysqli::query(): Couldn't fetch mysqli in /home/sites/unitest.co.uk/public_html/includes/register_user.inc.php on line 24 Warning: main(): Couldn't fetch mysqli in /home/sites/unitest.co.uk/public_html/includes/register_user.inc.php on line 27 Error: INSERT INTO signed_up(name, email, password) VALUES ('gptgeoff', 'up666315#myport.ac.uk', '$2y$10$JUi/eSNwbTnM4ZyWetEL6.ELSepLPKLkEiJdi4WYMyp/sEEAk9hKe')
The db_connect.php file works because I'm getting the "you have succesfuly connected to the database" displaying, the session variables are being passed and echoed out in both the echo statements and in the values of the $sql query so I am unable to understand why this has stopped working, can anyone advice please
db_connect.php
<?php
include_once 'psl-config.php'; // As functions.php is not included
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if(!$mysqli) {
die('error connecting to database');
}
echo 'you have succesfuly connected to the database'.'<br/><br/>';
?>
This line:
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
creates an object. It is an instance of the class mysqli. An object will always be true. Your if statement checks if $mysqli is false. This if statement is wrong, because whether the connection was successful or not the object will never be false.
Do not check for connection errors manually. Your connection failed and when it did PHP threw a warning. Please check your PHP configuration for error reporting, because you have probably warnings silenced. Also please enable mysqli error reporting. Insert this line before creating an instance of mysqli.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I'm trying to display a message upon a successful user registration however what I have doesn't seem to be working and just submits/refreshes the page. No message pops up even though data has successful been entered into the SQL database. Any tips or ideas?
<?php
require('php/connect.php');
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO `user` (username, password, email) VALUES ('$username', '$password', '$email')";
$result = mysql_query($query);
if($result){
echo $msg = "Successful Registration!";
}
}
?>
Learning PHP currently so sorry if there's a really obvious answer here!
Edit: Forgot to include echo. Just needed a second pair of eyes, sorry guys. Thanks for the tips!
First of all have this on consideration:
If you're getting started on PHP, please stop using mysql. It's deprecated, instead, you can use either PDO or MySQLi
As for your issue, your message is not being printed. Please make sure you echo the $msg variable:
$msg = "Successful Registration!";
echo $msg;
In mysqli a standard connection would be:
$DBConnect = new mysqli('serverName', 'userName', 'userPassword', 'dbName');
And that's it, that's all you need to start querying your database using mysqli.
For a mysql connection, try debugging it, see if there's a connection:
$connection = mysql_connect('localhost', 'userName', 'userPassword');
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
Try to echo message
if($result)
{
echo $msg = "Successful Registration!";
}
<?php
echo "Successfully registered!";
?>