How to Connect database MySql using PHP? - php

I followed a lot of tutorial on google/youtube but still unable to connect database using php. I coded exactly according to documentation for database connection but it doesn,t work.I have already created database named as userregistration using mysql dashboard.
Here is myindex.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Login and Registration</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="login-box">
<div class="row">
<div class="col-md-6 login-left">
<h2>Login Here</h2>
<form action="validation.php" method="post">
<div class="form-group">
<label>Username</label>
<input type="text" name="user" class="form-control" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
<div class="col-md-6 login-right">
<h2>Register Here</h2>
<form action="registration.php" method="post">
<div class="form-group">
<label>Username</label>
<input type="text" name="user" class="form-control" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Here is my Registration.php file:
<?php
session_start();
$con = mysqli_connect('localhost','root','');
mysqli_select_db($con, 'userregistration');
$name = $_POST['user'];
$pass = $_POST['password'];
$s = "select * from usertable where name='$name'";
$result = mysqli_query($con, $s);
$num = mysqli_num_rows($result);
if($num == 1){
echo "Username Already Taken";
}else{
$reg = "insert into usertable(name, password) values ('$name','$pass')";
mysqli_query($con, $reg);
echo "Registration Successful";
}
?>
Is there any error in my code?

Try using directly the connection with db name
based on patter
$con = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
try
$con = mysqli_connect('localhost','root','','userregistration');
and be sure your php page is in the correct path
eventually try adding a proper path or at least a relative path
<form action="./Registration.php" method="post">

Your PHP part looks alright. Maybe you can try to see if the PHP is able to make the connection by adding such a debugging code like how it is documented here, https://www.php.net/manual/en/function.mysqli-connect.php
if (!$con) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($con) . PHP_EOL;
Finally, MOST IMPORTANTLY, you should probably not be using this directly because this can introduce serious SQL-Injection vulnerabilities. Google a little more about the best practices. :)

Related

Information From Forum is Not Being Sent to Database

I have been working on this project for hours and need fresh eyes as to why the information from the forum is not being submitted into the database.
I have checked that the connection to the database was working. Whenever I try to submit an entry to the database, it shows that nothing goes wrong and goes to https://example.com/beta/index.php?post=success as it is supposed to but nothing except the auto_incremented id number shows up into the database.
My form page:
if(!session_id()){
session_start();
}
require('loginregister-master/includes/config.php');
if ($_SESSION['username'] !== admin ) {
header("Location: https://www.example.com/beta");
}
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: loginregister-master/login.php'); }
include('sec/HTTPS.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Post Blog</title>
<!-- Bootstrap Core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<script src="vendor/jquery/jquery.min.js"></script>
</head>
<body>
<form action="likesdislike/post.php" method="POST">
<div class="form-group">
<label>Title</label>
<input type="title" class="form-control" name="title' placeholder="Title">
</div>
<div class="form-group">
<label>Content</label>
<input type="content" class="form-control" name="content' placeholder="Content">
</div>
<div class="form-group">
<label>Date</label>
<input type="text" class="form-control" name="etad' placeholder="Date">
</div>
<div class="form-group">
<label>Author</label>
<input type="text" class="form-control" name="author' placeholder="author">
</div>
<div class="form-group">
<label>URL</label>
<input type="text" class="form-control" name="URL' placeholder="URL">
</div>
<button type="submit" name="submit">Submit</button>
</form>
</body>
</html>
The bit that 'should' handle the submission the database:
<?php
include('connect.php');
$title = mysqli_real_escape_string($link, $_POST['title']);
$content = mysqli_real_escape_string($link, $_POST['content']);
$etad = mysqli_real_escape_string($link, $_POST['etad']);
$author = mysqli_real_escape_string($link, $_POST['author']);
$URL = mysqli_real_escape_string($link, $_POST['URL']);
$sql = "INSERT INTO posts (title, content, etad, author, URL) VALUES ('" . $title . "', '" . $content . "', '" . $etad . "', '" . $author . "', '" . $URL . "')";
mysqli_query($link, $sql);
header("Location: https://www.example.com/beta/index.php?post=success");
?>
And of course, the bit that handles the connection to the database:
<?php
$link = mysqli_connect("localhost", "username", "password", "database_name");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
You have misplaced " in name of html tags. Just do it with "".
<form action="likesdislike/post.php" method="POST">
<div class="form-group">
<label>Title</label>
<input type="title" class="form-control" name="title" placeholder="Title">
</div>
<div class="form-group">
<label>Content</label>
<input type="content" class="form-control" name="content" placeholder="Content">
</div>
<div class="form-group">
<label>Date</label>
<input type="text" class="form-control" name="etad" placeholder="Date">
</div>
<div class="form-group">
<label>Author</label>
<input type="text" class="form-control" name="author" placeholder="author">
</div>
<div class="form-group">
<label>URL</label>
<input type="text" class="form-control" name="URL" placeholder="URL">
</div>
<button type="submit" name="submit">Submit</button>
</form>

404 when submitting form data to sql database

I keep submitting form input or attempting to do so I get a 404 with this PHP at the end of the url its in the top of the php snippit I am unsure if that is a clue to the issue. I have the action linked to insert.php I am unsure what is going on. Everything to me looks correct. But obviously its not. I've made sure the header('location: index.html') is correct. As another post suggested. Here is my code
HTML
<!Doctype html>
<html>
<head>
<title>Sign Up</title>
<link rel="stylesheet" href="css/live/app-d159020cbe.min.css">
<link rel="stylesheet" href="css/live/core-89ce772293.min.css">
</head>
<body>
<div class="containsignuptext">
<p>We believe the developer community is stronger togeather, We believe it takes the right community for us to reach the next stage in the future we believe in adding real tools to developers tool belts.</p>
</div>
<form action="insert.php" method="POST" accept-charset="UTF-8" role="form" id="loginForm">
<div class="form-group">
<div class="form-group">
<label for="login_email" class="sr-only">Full Name</label>
<input class="form-control input-lg" id="fullname" placeholder="Full Name" required="required" name="fullname" type="text">
</div>
<div class="form-group">
<label for="login_email" class="sr-only">Username</label>
<input class="form-control input-lg" id="username" placeholder="Username" required="required" name="username" type="text">
</div>
</div>
<div>
<label for="login_email" class="sr-only">Email</label>
<input class="form-control input-lg" id="email" placeholder="Email" required="required" name="email" type="text">
</div>
<div class="form-group">
<label for="login_password" class="sr-only">Password</label>
<input class="form-control input-lg" id="password" placeholder="Password" required="required" name="password" type="password">
<div>
<label for="login_email" class="sr-only">Codelangs</label>
<input class="form-control input-lg" id="codelang" placeholder="Code Language You Like the Most" required="required" name="codelangs" type="text">
</div>
<button method="POST" type="submit" class="btn btn-lg btn-primary btn-block ladda-button" data-style="zoom-in" type="submit" name="insert">
<span class="ladda-label">Get Hacking</span>
</button>
</form>
</body>
</html>
PHP
<?php echo $_SERVER['PHP_SELF']; ?>
I get that in the url idk if it helps the rest is the inser.php code.
<?php
$servername = "localhost";
$username = "Placeholder";
$pass = "FakeForShow";
$dbname = "sign up new";
$fullname=$_POST['fullname'];
$username=$_POST['username'];
$email=$_POST['email'];
$password=$_POST['password'];
$codelangs=$_POST['codelangs'];
// Create connection
$conn = new mysqli($servername, $username, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO newusers (fullname, username, password, email, codelang)
VALUES ( '$fullname', '$username', '$email', '$password', '$codelangs');";
if ($conn->query($sql) === TRUE) {
header("location: index.html");
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Your database connection should be similar to this.
$s = 'localhost';
$u = 'root';
$p = 'yourUsername';
$d = 'yourPassword';
$mysqli = new mysqli($s, $u, $p, $d);
Check to see if the butt is clicked first.
if(isset($_POST['insert'])){
Do some Error Checks like this you need to add to this this is very basic.
$fullname=$_POST['fullname'];
$username=$_POST['username'];
$email=$_POST['email'];
$password=$_POST['password'];
$codelangs=$_POST['codelangs'];
$alert = '';
$errorFullname = '';
if($_POST['fullname'] == '' || $_POST['username'] || $_POST['email'] || $_POST['password']){
if($_POST['fullname'] == ''){$errorFullname "Cannot be empty.";}//and so on...
$alert = "All fields are required.";} else {
If no Errors insert. Encrypt your passwords before inserting them.
$hashedWord = password_hash($password, PASSWORD_BCRYPT, array("cost" => 17));
$insertdata = $mysqli->prepare("INSERT INTO newusers (fullname, username, password, email, codelang) VALUES('"$fullname"', '"$username"', '"$hashedWord"', '"$email"', '"$codelangs"') ");
$insertdata->execute();
$insertdata->close();
header("location: index.html");
}
}
include 'YourHtmlPage';
You can call the error messages like this.
<div class="form-group">
<label for="login_email" class="sr-only">Full Name</label>
<input class="form-control input-lg" id="fullname" placeholder="Full Name" required="required" name="fullname" type="text">
</div>
<div><?php echo $errorFullname; ?></div>
You can use something like this to check the hashed password. Run a select and match it with what they typed.
password_verify($passwordTheyTyped, $YourHashedPassFromTheDatabase);
Hope it helps a little.
This might help you.
The HTML Code : index.php
<!Doctype html>
<html>
<head>
<title>Sign Up</title>
<link rel="stylesheet" href="css/live/app-d159020cbe.min.css">
<link rel="stylesheet" href="css/live/core-89ce772293.min.css">
</head>
<body>
<div class="containsignuptext">
<p>We believe the developer community is stronger togeather, We believe it takes the right community for us to reach the next stage in the future we believe in adding real tools to developers tool belts.</p>
</div>
<form action="insert.php" method="POST" accept-charset="UTF-8" role="form" id="loginForm">
<div class="form-group">
<label for="login_email" class="sr-only">Username</label>
<input class="form-control input-lg" id="username" placeholder="Username" required="required" name="username" type="text">
</div>
<!-- Other form elements-->
<button method="POST" type="submit" class="btn btn-lg btn-primary btn-block ladda-button" data-style="zoom-in" type="submit" name="insert">
<span class="ladda-label">Get Hacking</span>
</button>
</form>
</body>
</html>
The PHP Code : insert.php
<?php
$servername = "localhost";
$db_username = "DB_USER_NAME";
$db_pass = "DB_USER_PASSWORD";
$dbname = "DB_NAME";
$username = $_POST['username'];
// Other POST elements
$conn = new mysqli($servername, $db_username, $db_pass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO newusers (username) VALUES ('$username');";
if ($conn->query($sql) === TRUE) {
header("location: index.php");
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
You can add more form elements, Javascript Validations etc as per your requirement.

what am i doing wrong in this register.php php code?

I am trying to make a registration form using php and mysql.
i m using xampp and phpmyadmin from that and my sql queries on table 'user' is working fine.
but when i try to insert using php code it shows "user registration failed".
below is my code
register.php
<?php
require('includes/connect.php');
// If the values are posted, insert them into the database.
if (isset($_POST['username']) && isset($_POST['psw'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['psw'];
$query = "INSERT INTO `user` (username, password, email) VALUES('$username', '$password', '$email')";
$result = mysqli_query($connection, $query);
if($result){
$smsg = "User Created Successfully.";
}else{
$fmsg ="User Registration Failed";
}
}
?>
<html>
<head>
<title>BondOnNet | Register</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<!-- JS -->
<script src="js/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="js/jquery.jcarousel.pack.js" type="text/javascript"></script>
<script src="js/jquery-func.js" type="text/javascript"></script>
<!-- End JS -->
<link rel="stylesheet" type="text/css" href="css/register.css">
</head>
<body>
<div id="Register_header">
<h1 id="logo">BondOnNet</h1>
</div>
<div id="register_container">
<form method="POST" style="border:1px solid #ccc">
<?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?>
<?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?>
<div class="imgcontainer">
<img src="images/avatar.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<input type="checkbox" checked="checked"> Remember me
<p>By creating an account you agree to our Terms & Privacy</p>
<div class="clearfix">
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</div>
</body>
</html>
connect.php
<?php
$connection = mysqli_connect('localhost', 'root', '');
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'test');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
?>
I tried so many small changes in code but none of it worked!
Plz help me sort out what i m doing wrong
Use this for detecting errors:
mysqli_connect_errno() - Returns the error code from last connect call
mysqli_connect_error() - Returns a string description of the last connect error
mysqli_errno() - Returns the error code for the most recent function call
mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation
For more information and exemples: http://php.net/manual/en/mysqli.error.php

PHP not being able to pick data from HTML form

My PHP page is unable to pick values from HTML form. It's sending blank strings to database. Here is my HTML and PHP code. Please find error. I am new to PHP, unable to solve the problem.
my html page:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>LOGIN</title>
<link rel="stylesheet" href="css/reset.css">
<link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'>
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!-- Mixins-->
<!-- Pen Title-->
<div class="pen-title">
<h1>SYNCHPHONY</h1>
</div>
<div class="rerun">Rerun Pen</div>
<div class="container">
<div class="card"></div>
<div class="card">
<h1 class="title">Login</h1>
<form name="login" action="login.php" method="POST">
<div class="input-container">
<input type="text" id="loginid" required="required"/>
<label for="loginid">Login ID</label>
<div class="bar"></div>
</div>
<div class="input-container">
<input type="password" id="password" required="required"/>
<label for="password">Password</label>
<div class="bar"></div>
</div>
<div class="button-container">
<button><span>Go</span></button>
</div>
</form>
</div>
<div class="card alt">
<div class="toggle"></div>
<h1 class="title">Register
<div class="close"></div>
</h1>
<form name="register" action="register.php" method="POST">
<div class="input-container">
<input type="text" id="loginid" required="loginid"/>
<label for="loginid">Login ID</label>
<div class="bar"></div>
</div>
<div class="input-container">
<input type="password" id="password" required="required"/>
<label for="password">Password</label>
<div class="bar"></div>
</div>
<div class="button-container">
<button value'submitb'><span>Next</span></button>
</div>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
my php page:
**strong text** <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "syncphony";
$loginid="";
$password="";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['loginid'])){ $loginid = $_POST['loginid']; }
if(isset($_POST['password'])){ $password = $_POST['password']; }
// Escape user inputs for security
$loginid = mysqli_real_escape_string($conn,$loginid);
$password = mysqli_real_escape_string($conn,$password);
// attempt insert query execution
$sql = "INSERT INTO users (loginid, password ) VALUES ('$loginid', '$password')";
if(mysqli_query($conn, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
// close connection
mysqli_close($conn);
?>
The inputs inside your form tag do not have names. Try this for login:
<input type="text" id="loginid" required="required" name="loginid"/>
and this for password:
<input type="password" id="password" required="required" name="password"/>
It would be nice if you would protect your users against XSS attacks and to use encryption when you store a password. Also, you should structure your code and make sure your HTML is valid.

Cannot insert form data into a MySQL database using PHP

I am trying to insert data submitted in a form, into a MySQL Database, and I can't see the problem in my code(except for MySQL injection, that I will work to resolve after actually being able to insert any data). I have searched in Stack Overflow, and found someone who probably worked by the same manual, but I work in localhost, he's on GoDaddy. The solution given there doesn't work for me.
Here is my code for the HTML and the PHP code:
<?php
require'connection/connect.php';
?>
<?php
if(isset($_POST['Register'])){
session_start();
$Fname = $_POST['FirstName'];
$Lname = $_POST['LastName'];
$Email = $_POST['Email'];
$pw = $_POST['Password'];
$sql= $con->query("INSERT INTO user (Fname,Lname,Email,Password) values('{$Fname}', '{$Lname}', '{$Email}', '{$pw}')");
}
?>
<!DOCTYPE html >
<html>
<head>
<link href="css/Master.css" rel="stylesheet" type="text/css" />
<link href="css/Menu.css" rel="stylesheet" type="text/css" />
<title>Register</title>
</head>
<body>
<div class="container">
<div class="header">
</div>
<div class="menu">
<div id="NavBar">
<nav>
<ul>
<li>
Login
</li>
<li>
Register
</li>
</ul>
</nav>
</div>
</div>
<div class="leftBody"></div>
<div class="rightBody">
<form action="" method="post" name="RegisterForm" id="RegisterForm">
<div class="FormElement">
<input name="FirstName" id="FirstName" type="text" placeholder="First Name" class="TField">
</div><br>
<div class="FormElement">
<input name="LastName" id="LastName" type="text" placeholder="Last Name" class="TField">
</div><br>
<div class="FormElement">
<input name="Email" id="Email" type="email" placeholder="E-Mail" class="TField">
</div><br>
<div class="FormElement">
<input name="Password" id="Password" type="password" placeholder="Password" class="TField">
</div><br>
<input name="Register" id="Register" type="button" value="Register" class="regButton">
</form>
</div>
<div class="footer"></div>
</div>
</body>
</html>
And this is my connection.php file:
That it does show that it connects.
<?php
$host="localhost";
$username="root";
$password="";
$dataBase="users";
$con=mysqli_connect($host,$username,$password,$dataBase);
if (!$con) {
die("Could not connect: " . mysqli_error());
}
echo "Connected successfully";
?>
And a picture of my database in phpMyAdmin:
Database
I have tried also using this line like this for some reason, but to no avail.:
$sql= $con->query("INSERT INTO user
(Fname,Lname,Email,Password)
values ('Fname', 'Lname', 'Email', 'pw')");
i didn't see submit button that actually submit the form. So if i am not wrong please try to use
<input name="Register" id="Register" type="submit" value="Register" class="regButton">
your code should be run
$sql= $con->query("INSERT INTO user
(Fname,Lname,Email,Password)
VALUES('$Fname', '$Lname', '$Email', '$pw')");

Categories