Hi I'm trying to insert data in my database. But I keep on getting the same error for example:
Error: INSERT INTO users (username, password) VALUES ('fff', '$2y$10$YUd1AErIj4RGRnjkFkYlkOn.s9OV62sq8.HVGO2jeE8dSthpgp6ey');
without any details which is very frustrating. I'm new to PHP and SQL so it's not the best written code ever and I know I should use prepared statements.
<?php
require_once '../connection/connection.php';
/**
* Created by PhpStorm.
* User: ezrab
* Date: 3/14/2018
* Time: 5:40 PM
*/
$username = $_POST['username'];
$password = $_POST['password'];
//var_dump($hashed_password);
if (isset($_POST['submit'])) {
if (!empty($username) || !empty($password)) {
if (preg_match('/^[A-Za-z]?[A-Za-z ]*$/', $username) || preg_match('/^[A-Za-z]?[A-Za-z ]*$/', $password)) {
$hashPwd = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$hashPwd');";
if ($conn->query($sql) === TRUE) {
echo "Worked!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "You can't use certain characters.";
}
} else {
echo "You have to fill in all fields.";
}
} else {
echo "THOU SHALL NOT PASS!";
}
$conn->close();
EDIT: Added my connection.php file for more information.
<?php
$servername = "-----";
$username = "-----";
$password = "------";
$dbname = "------";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
EDIT:
Take
$conn->close();
out of connection.php and problem should be solved
You were opening and then immediately closing the connection before a query could be made
Related
I want to set up a website with a form in it. The form will transfer the data to the DB, but I think it is not safe to let the personal data in the DB which is external reachable.
So I thought I should transfer the data via PHP from the DB1(server1 - external reachable) to DB2(server2 - only internal reachable).
The following picture should help to know what I am searching for.
Is there any names/methods to google for?
From php you just have to create a new connection for DB2.
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
$servername2 = "localhost";
$username2 = "database2";
$password2 = "xxxxxxxx";
$dbname2 = "database2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn2 = new mysqli($servername2, $username2, $password2, $dbname2);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
if ($conn2->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn2->error;
}
$conn->close();
$conn2->close();
?>
I need to send md5 hashed password to database.
<?php
$username = filter_input(INPUT_POST, 'name');
$password = filter_input(INPUT_POST, 'password');
print_r($_POST['name']);
if (empty($username)){
echo "Username should not be empty"; die();
}
if (empty($password)){
echo "Password should not be empty"; die();
}
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "db_account";
//create connection
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_error()){
die('Connect Error ('. mysqli_connect_error() .') '
. mysqli_connect_error());
} else{
$sql = "INSERT INTO t_account (name, pwd)
values ('{$username}','MD5({$password})')";
if ($conn->query($sql)){
echo "Account was created successfully!";
}
else{
echo "Error: ". $sql."<br>". $conn->error;
}
$conn->close();
}
?>
When I fill register form with password for example 123456 it sends it to database like this (MD5)123456 but not as a hashed code.
Also after successfull registration it only shows text after #echo, is possible to redirect user to another page?
Try to use the PHP md5() function:
$password = md5(filter_input(INPUT_POST, 'password'));
Also your statement:
$sql = "INSERT INTO t_account (name, pwd)
values ('{$username}','{$password}')";
I strongly suggest you use prepared statements. Not hard to learn and time well invested.
Good Day developers outthere! 😊😊
I just wanna ask what is the problem with my code, I'm trying to make a webpage using html,css,php and database. Now I already created a php in my html form and my database is already connected, but everytime I submit the information in the html form I created, nothing appeared in my database.
<?php
if(isset($_POST['save'])){
$FName = $_POST['FName'];
$MName = $_POST['MName'];
echo "Successfully Added";
$sql= "INSERT INTO 'tbstudinfo' (Transaction_Number, First_Name, `Middle_Name') VALUES ('000',$FName,$MName)";
} else{
echo "<p>Insertion Failed.</p>";
}
?>
Just as #executable mentioned, you are defining query in your code but not executing it.
Define Connection Object (Mysqli, PDO..)
Prepare Query and Bind Variables
Execute your query
Here's an example using prepared statements
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if( isset($_POST['save']) ){
// prepare and bind
$stmt = $conn->prepare("INSERT INTO 'tbstudinfo' (Transaction_Number, First_Name, Middle_Name) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $transaction_number, $FName, $MName);
// set parameters and execute
$transaction_number = '000';
$FName= $_POST['FName'];
$MName= $_POST['MName'];
$stmt->execute();
echo "Successfully Added";
}else{
echo "<p>Nothing Posted</p>";
}
W3Schools and PHP.Net both have pretty good examples about how to use prepared statements to make your SQL Query more secure from SQL Injections.
You simply don't execute your query. Using MySQLi :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "dbthesis";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['save'])){
$FName = $_POST['FName'];
$MName = $_POST['MName'];
$sql = "INSERT INTO tbstudinfo (Transaction_Number, First_Name, Middle_Name) VALUES ('000', '$FName', '$MName')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Added";
} else {
echo "<p>Insertion Failed.</p>";
}
}
$conn->close();
You only making a query, not running query. This this code
$FName = $_POST['FName'];
$MName = $_POST['MName'];
$sql = "INSERT INTO tbstudioinfo (Transaction_Number, First_Name, Middle_Name) VALUES ('000','$FName','$MName')";
// code below runs your query
if (mysqli_query($conn, $sql)) {
echo "Successfully Added";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
I have a script that updates/creates user from an iOS device. Now i want to have the script also check if the user already exists in the database. I am going to restrict this to username for now, so no more than ONE unique username may exist. I have an if-statement in my PHP but i cannot get it to work - help please :).
<?php
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$db_name = 'dbname';
$db_user = 'dbuser';
$db_password = 'dbpass';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
$userexists = mysql_query("SELECT * FROM users WHERE username='$username'");
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
}
if(mysql_num_rows($userexists) != 0) {
echo '{"success":0,"error_message":"Username Exist."}';
}
else {
$stmt = $mysqli->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
$password = md5($password);
$stmt->bind_param('sss', $username, $password, $email);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
error_log("Success: $success");
if ($success > 0) {
error_log("User '$username' created.");
echo '{"success":1}';
}
else {
echo '{"success":0,"error_message":"Username Exist."}';
}
}
}
else {
echo '{"success":0,"error_message":"Passwords does not match."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Username."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
You could SELECTthe table before trying to insert username. If it already exists (= you have a result) you dont simply insert.
Better yet, use ON DUPLICATE IGNORE or something like that.
I have problem with MySQL database, I can't insert the information into the table. My php code seems to work, but when I run it nothing happens.
<?php
$servername = "localhost";
$fname = "fname";
$lname = "lname";
$klas = "klas";
$nomer = "nomer";
$file = "dom";
$dbname = "homeworks";
$conn = new mysqli($servername, $fname, $lname,$klas,$file,$dbname);
$sql = "INSERT INTO student (fname, lname,klas,file)
VALUES ($servername, $fname, $lname,$klas,$file,)";
?>
You have three main problems in your code:
You're still not connected to the database
Only constructing and not executing
Having not matched parameters in the insert values
Solution :
1. Make a connection first
$conn = new mysqli($servername, $username, $password, $dbname);
The Parameter $servername, $username, $password, $dbname is obviously your hostname, Database Username, Password and the Database name
You should not have your table name or column names in the connection parameters
2. Construct the parameters which matches the coloumn name and variables correctly
$sql = "INSERT INTO student (fname, lname,klas,file)
VALUES ($fname, $lname,$klas,$file)";
3. Execute Your Query :
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Note :
Also it's good practice to close your connection once you are done
$conn->close();
So, you should be having something like this
<?php
$servername = "localhost";
$username = "YourDBUsername";
$password = "YourDBPassword";
$fname = "fname";
$lname = "lname";
$klas = "klas";
$nomer = "nomer";
$file = "dom";
$dbname = "homeworks"; //Hope you will have your db name here
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "
INSERT INTO student (fname, lname,klas,file) VALUES
('$fname'
,'$lname'
,'$klas'
,'$file');
";
if ($conn->query($sql) === TRUE) {
echo "New record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Advice :
Always use prepared statements else clean your inputs before you insert.
Your connection should look something like this. link
<?php
//change the data into your connection data
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
You made your query but didn't execute it.
if (mysqli_query($conn, $sql)) {
echo 'records created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($conn);
}