I can't seem to find out why my PHP code won't allow me to store the info in MySQL when I click the submit button. Can someone tell me whats wrong with the code below?
I want to get it to the point where users submit their registration form and their info can get moved over to a MySQL database. Then, I want the users to be taken to my index.html file.
Any help is appreciated.
Thanks
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$mysql_database = "21st";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Could not connect database");
mysqli_select_db($conn, $mysql_database) or die("Could not select database");
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
if ($password == $password2) {
$sql = "INSERT INTO members (username, email, password) VALUES ('$userrname','$email','$password')";
} else {
echo "Your passwords must match";
}
?>
Try this using mysqli_query to actually run the query. When you set $sql all that did was set a variable named $sql to the query. Also note you set the variable $userrname in the query when it should be $username as set from the $_POST directly above. My adjusted version of your code below:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$mysql_database = "21st";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Could not connect database");
mysqli_select_db($conn, $mysql_database) or die("Could not select database");
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
if ($password === $password2) {
// Set the query.
$sql = "INSERT INTO members (username, email, password)"
. " VALUES (?, ?, ?)"
;
// Bind the values to the query.
mysqli_stmt_bind_param($sql, 'sss', $username, $email, $password);
// Run the query.
mysqli_query($conn, $sql);
// Free the result set.
mysqli_free_result($sql);
// Close the connection.
mysqli_close($conn);
}
else {
echo "Your passwords must match";
}
Related
Still loggin in even if the username and password is incorrect and also logins even if the value is null
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "login";
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die ("unable to connect");
}
if ($_POST) {
$uname = $_POST ["username"];
$pass = $_POST ["password"];
$sql = "SELECT * FROM users WHERE username = '$uname' AND password = '$pass' LIMIT 1 ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1){
include("graph.php");
} else {
echo "Incorrect";
}
}
?>
First of all and very important it that you are open to SQL Injection attack, so you should use prepared statements, here is how should use your code, but instead of echo "Incorrect"; you should render different answer for each case:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "login";
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die ("unable to connect");
}
if (isset($_POST["username"]) && isset($_POST["password"])) { // Check if you have posted data via POST
$uname = $_POST["username"];
$pass = $_POST["password"];
$sql = "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1 ";
if($stmt = $conn->prepare($sql)) { // Check for MySQL errors
$stmt->bind_param('ss', $uname, $pass);
if ($stmt->execute()) {
$stmt->close();
include("graph.php");
} else { // There is a problem with your SELECT // bind params
echo "Incorrect";
}
} else { // You should handle mysql errors here
echo "Incorrect";
}
} else { // You don't have POST data
echo "Incorrect";
}
?>
Prepared statements
Like #Kuya notice you have and many other problems, there is a lot of tutorials in Google about implementation of login system.
You must check the post request with isset() in php like this :
<?php
if (isset($_POST["username"] && isset($_POST["password"]))) {
//..... Your code here
}else {
echo "Incorrect password or username";
}
?>
I have been trying to connect to the mysql server through php code, but was unable to. Please help me solve this problem.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$bool = true;
mysql_connect("localhost", "root","rot_darshan") or die("Cannot connect to server"); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("Select * from users"); //Query the users table
while($row = mysql_fetch_array($query)) //display all rows from query
{
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
if($username == $table_users) // checks if there are any matching fields
{
$bool = false; // sets bool to false
Print '<script>alert("Username has been taken!");</script>'; //Prompts the user
Print '<script>window.location.assign("register.php");</script>'; // redirects to register.php
}
}
if($bool) // checks if bool is true
{
mysql_query("INSERT INTO users (username, password,fname,lname,email) VALUES ('$username','$password','$fname','$lname','$email')"); //Inserts the value to table users
Print '<script>alert("Successfully Registered!");</script>'; // Prompts the user
Print '<script>window.location.assign("register.php");</script>'; // redirects to register.php
}
}
?>
Please avoid the native mysql_* functions. These are depricated and will be removed:
http://php.net/manual/en/function.mysql-connect.php
Try to follow (mysqli_*):
https://www.w3schools.com/php/php_mysql_connect.asp
$servername = "localhost";
$username = "root";
$password = "rot_darshan";
$database = "first_db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//Query example
$result = $conn->query("SELECT * FROM users")
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["username"]);
}
If these don't work, check your database credentials (username, password, database name and/or port)
Check for username,password by externally connecting .also replace localhost with 127.0.0.1 or your lan ip.
Check SELECT User, Host FROM mysql.user;
This is my CODE, id do not know where is the mistake but this code does not create any information on the database.
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db($dbhandle);
if(isset($_POST['user']) && isset($_POST['pass'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
$query = mysql_query("SELECT * FROM users WHERE Username='$user'");
if(mysql_num_rows($query) > 0 ) { //check if there is already an entry for that username
echo "Username already exists!";
}else{
mysql_query("INSERT INTO users (Username, Password) VALUES ('$user', '$pass')");
header("location:begin.html");
}
}
mysql_close();
?>
Forget database name here.
change this:
$selected = mysql_select_db($dbhandle);
With
$selected = mysql_select_db($dbname,$dbhandle);
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db($dbhandle);
In above code you are not passing any database name to use, you should pass a database name instead of connection link to mysql_select_db($dbhandle);
like
$db_selected = mysql_select_db('foo', $link);
For reference
http://php.net/manual/en/function.mysql-select-db.php
Hi first of all Please use mysqli or PDO as mysql is depreciated and completely removed from PHP7.
Now your problem . You are not included database name in your mysql_select_db. It should be
$selected = mysql_select_db($dbhandle , $databasename) or die(mysql_error($dbhandle));
Always remember try to echo error after any query this will solve your problem in many cases
Its a simple registration with username and password, but when I try to insert it to the database it always fails and I don't know why, can someone help me with this?
include "db.php";
if (isset($_POST['submit']))
{
$username= $_POST['leguser'] ;
$password= $_POST['legpass'] ;
$pwhash = password_hash($password, PASSWORD_DEFAULT) ;
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
echo var_dump ($username);
echo var_dump ($password);
echo var_dump ($pwhash);
$sql = "SELECT * FROM tbl_users WHERE fld_username = '$username'";
$result = $conn->query($sql);
if ($result->num_rows === 1) {
echo "<script>alert('Username already used!');</script>"; }
else
{
$q = "INSERT INTO `tbl_users` (`fld_username`) VALUES ('$username')";
$result = mysql_query($q);
if ($result) {
echo 'success';
} else {
echo 'failure';
}
}
This is the code of the database connection (db.php)
<?php
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'rsi_db';
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
}
By the way I only want to input only one data on the database which is the username, for me not to get complicated with every data that I want to put in the future.
I have decided for security to convert my simple php with mysql code to PDO,since it will tighten my security.My old code:
$host = "localhost";
$user = "username";
$pass = "pass";
$database = "mydatabase";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$name=$_POST['name'];
$message=$_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$query="INSERT INTO table (date_time, name, message,ip) VALUES (NOW(),'$name','$message','$ip')";
If (mysql_query($query,$linkID)){
//Success
}else{
//Failure
}
My new code is:
$hostname = 'localhost';
$username = 'username';
$password = 'pass';
$dbname = 'mydatabase';
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
if($_POST['name'] && $_POST['message']) {
$name = $_POST['name'];
$message = $_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO table (date_time, name, message,ip)VALUES (NOW(), :name, :message,'$ip')";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':message', $message, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "OK";
}
}
It's very strange that when i point my browser to index.php?name=someName&message=someMessage my PDO code won't echo a single thing(even echo "ok" ) or an error so i can fugure out where is the problem.
I can confirm that no data is inserted to the database.
I've even added try catch but nothing changed. My php is supporting PDO and the simple Mysql code is working.
Any ideas? Thanks
In your case,
if($_POST['name'] && $_POST['message']) {
Should be:
if($_GET['name'] && $_GET['message']) {