I have been trying to use mysqli_query to connect to database define in an external file but am getting an repeated error as undefined $conn
index.php
<?php
require 'connect.in.php';
include 'loginform.php';
?>
connect.in.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbase = "users";
$conn = mysqli_connect($servername,$username,$password);
if($conn ||!mysqli_select_db($dbase)){
die('error message');
}
?>
loginform.php
<?php
if(isset($_POST['username']) && isset($_POST['password'])){
$username = 'username';
$password = 'password';
if(!empty($username) && !empty($password)){
$query = "SELECT 'id' FROM 'user_list' WHERE 'username'= '$username' AND 'password' = '$password'";
if(mysqli_query($conn, $query)){
echo "correct";
}
else{
echo "false";
}
}
}
?>
<form method="post">
Username:<input type="text" name="username">
Password:<input type="password" name="password">
<input type="submit" value="Login">
</form>
also is it possible to incorporate CSS and Bootstrap in this php files say for loginform.php?
Don't forget to tell mysqli_connect() function what database you are using. I hate to use W3Schools but take a look here, the 4th parameter is the DB you want to use.
connect.in.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbase = "users";
$conn = mysqli_connect($servername,$username,$password, $dbase);
if($conn ||!mysqli_select_db($dbase)){
die('error message');
}
?>
Generally you would want all your CSS and JS files in the <head> element of your index page or your master page. Essentially you could just add the files in your loginform.php file at the top but i would suggest not doing so and place them in your index.php file.
Related
Why can't I login to my index.php page its just getting stucked in my login.php page. Please help. Thanks.
<?php
session_start();
$conn = new PDO('mysql:host = localhost;dbname=userdb','root','');
if (isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = $conn->prepare("SELECT COUNT('userID') FROM 'tbl_account' WHERE 'username' = '$username' AND 'password' = '$password' ");
$query->execute();
$count = $query->fetchColoumn();
if ($count == 1){
$_SESSION['username'] = $username;
header("location : index.php");
exit();
}else{
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action = "?" method = "POST">
<input type = "text" name="username"><br> //username
<input type = "password" name = "password"><br> //password
<input type = "submit" name = "submit" value = "Login"> /button
</form>
</body>
</html>
where could probably my mistake? on my PDO? on my prepared statement? TIA
1)form action missing.
2)isset($_POST['login']) wrong name checking in if condition.
3)prepared statement have lots of issue.
try something like this
<?php
session_start();
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "root"; //username
$password = ""; //password
$mysql_database = "userdb"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT * FROM tbl_account WHERE username =? AND password =? ");
$stmt->bind_param('ss',$username,$password);
$stmt->execute();
$get_result= $stmt->get_result();
$row_count= $get_result->num_rows;
$stmt->close();
$conn->close();
if ($row_count>0){
$_SESSION['username'] = $username;
header("location:index.php");
exit();
}else{
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action = "login.php" method = "POST">
<input type = "text" name="username"><br> //username
<input type = "password" name = "password"><br> //password
<input type = "submit" name = "submit" value = "Login"> /button
</form>
</body>
</html>
its syntax to use an exit(); after any header('location [...]') calls, you're missing this in your code which could be the reason why your page does nothing.
Also, I'd really like to touch up on some security notes: what the hell is that?
PDO has pre-written functions to allow you the full dynamics of a connection with security, they are there to be used; as it stands, your SQL statement is a security risk as you're directly inserting untrusted data into a statement without stripping it of injections.
Heres an example you could use to secure this:
class DB extends PDO
{
function __construct(
$dsn = 'mysql:host=localhost;dbname=kida',
$username = 'root',
$password = 'root'
) {
try {
parent::__construct($dsn, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function query($statement, array $parameters = array())
{
$stmp = parent::Prepare($statement);
$i = 1;
foreach($parameters as $parameter) {
$stmp->bindParam($i, $parameter);
$i++;
}
$stmp->execute();
return $stmp->FetchAll();
}
}
$Con = new DB();
$username = "example";
$row = $Con->query("SELECT * FROM table WHERE username = ?", [$username]);
You have wrongly used prepared statement.
You should write,
$query = $conn->prepare("SELECT COUNT('userID') FROM REGISTRY WHERE name = ? AND password' = ?");
$query->bindParam(':name', $username);
$query->bindParam(':password', $password);
$query->execute();
$result_rows = $query->fetchColumn(); // get result
Check this link for more detail.
Suggestion:- also add exit; after header tag to stop execution of afterward code.
try and change this code to
"SELECT COUNT('userID') FROM 'tbl_account' WHERE 'username' = '$username' AND 'password' = '$password' ");
put semicolon inside the quotes and on the outside as well
"SELECT userID FROM tab1_account WHERE username='$username' AND password='$password';";
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Php form for MySQL</title>
</head>
<body>
<form action="home.php" method="post">
<p>
<label for="table">Name your Table</label>
<input type="text" name="table" id="table">
</p>
<p>
<label for="firstName">First Name:</label>
<input type="text" name="firstname" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<button name="submit" type="submit" value="submit">Create Table</button>
</form>
if (isset($_POST['submit'])){
//enter database details
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$table = $_POST['table'];
// Create a MySQL table in the selected database
mysqli_query("CREATE TABLE $table (
firstname VARCHAR(30),
lastname VARCHAR(30),
email VARCHAR(50))") or die(mysql_error());
if ($conn->query($sql) === TRUE) {
echo "Table account created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
if(isset($_POST['firstname']) || ($_POST['lastname']) || ($_POST['email']))
{
$order="INSERT INTO $table (firstname,lastname,email) VALUES ('$firstname','$lastname','$email')";
$result = mysqli_query($order) or die (mysql_error());
}
mysqli_close($conn);
}
?>
</body>
</html>
I'm trying to allow the user to pick a name for the database and was stuck. I get an error
Access denied for user ''#'localhost' (using password: NO)
Picture of what I want:
I don't know what to do. Hope you can help. Thanks
The error you're getting means you're not providing valid credentials to connect to the database. Don't update them in your question, because these details should be private, but you need to change the code:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
to be the actual values. For instance, if your mysql username is 'tomi', the username line would look like this:
$username = "tomi";
You don't really have a database named 'database' do you? And if your actual password is 'password' you need to change it to something more secure.
You open a mysqli connection, and then use mysql_query to make a query, when it should be mysqli_query. mysql_* and mysqli_* are very different things, and you should never use mysql_* anymore. After changing this, check your authentication details. As long as you're on a private machine, maybe use var_dump() to look at them and make sure they're what you expect them to be. It looks like they might be getting passed into mysqli as empty strings. If your auth details are absolutely correct, double check that the given user in the database actually has the required privileges.
Editing my top answer with the full php code that I think will work for you:
<?php
if (isset($_POST['submit'])){
//enter database details
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo "Failed to connect: (" . $conn->connect_error . ") ";
}
$table = $_POST['table'];
// SQL to Create a table in the selected database
$sql = "CREATE TABLE $table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30),
lastname VARCHAR(30),
email VARCHAR(50))";
if ($conn->query($sql) === TRUE) {
echo "Table account created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// Check connection
if (!$conn) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
if(isset($_POST['firstname']) || isset($_POST['lastname']) || isset($_POST['email'])) {
$order="INSERT INTO $table (firstname,lastname,email) VALUES ('$firstname','$lastname','$email')";
if ($conn->query($order) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $order . "<br>" . $conn->error;
}
}
$conn->close();
}
?>
IMPORTANT:
1)
Make sure you enter the correct database details at the top of the php code. For example for me with xampp on windows it is:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
where I have previously created the database "database" manualy.
2) If you want to make sure in your later part of the code that all fields are NOT empty, you might prefer to use && (and) instead of || (or) for your conditions in the if. Currently it will run even as long as ANY of the fields are filled in, even if the rest of the fields are EMPTY.
Example:
if(isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['email'])) {
instead of:
if(isset($_POST['firstname']) || isset($_POST['lastname']) || isset($_POST['email'])) {
I also highly suggest you check out the different ways to implement MySQLi with php; for example
Creating tables: http://www.w3schools.com/php/php_mysql_create_table.asp
the $_POST array does not get updated for some reason, not sure why.
here is my code, written in a file called database.php:
$user = 'root';
$password = '';
$db = 'comments_schema';
$host = 'localhost:3306';
$mysqli = mysqli_connect('localhost', $user, $password, $db);
$field1_name = "";
if(isset($_POST['field1_name'])) {
$field1_name = $_POST['field1_name'];
}
else {
echo "something is wrong here";
}
$field_name = mysqli_real_escape_string($mysqli, $field1_name);
$sql = 'INSERT INTO parent_comment(commentid, comment) VALUES
('.commentid.', '.$field_name.')';
$result = $mysqli->query($sql);
Here is my index.html portion for that part:
<form action="database.php" method="post">
Comments: <input type="text" name="field1_name"/>
<input type="Submit" name="Submit" value="submit query"/>
</form>
Any reason why isset always returns false in this case?
EDIT: I don't know if this is the case but check your max_input_vars value not to be a low number in php.ini
php_value max_input_vars 6000 //6K is the value you need
//first if checks if the form was submitted first, so you don't always display the error.
if(isset($_POST['Submit'])){
$user = 'root';
$password = '';
$db = 'comments_schema';
$host = 'localhost:3306';
$mysqli = mysqli_connect('localhost', $user, $password, $db);
$field1_name = $_POST['field1_name'] ?? ""; //Use only if you are using PHP 7+ Otherwise leave the code as it was but wrap it inside the outer if.
if(empty($field_name)){
echo "something is wrong here";
}
$field_name = mysqli_real_escape_string($mysqli, $field1_name);
$sql = 'INSERT INTO parent_comment(commentid, comment) VALUES ('.commentid.', '.$field_name.')';
$result = $mysqli->query($sql);
}
More info: https://lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator
I am trying to create a register/login html/php script. I created a database and I believe my html/php code is correct. I was wondering if I am missing something small. Here is my code so far.
Here is the database
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
if(isset($_POST["submit"]))
{
$User = "**";
$Password = "**";
$Database = "member";
$Host = "localhost";
$con = mysqli_connect($Host, $User, $Password);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,$Database);
$myusername = $_POST["username"];
$mypassword = $_POST["password"];
$sql = "INSERT INTO member (username, password) VALUES ('$myusername','$mypassword')";
mysqli_query($con,$sql);
mysqli_commit($con);
mysqli_close($con);
echo "Thank You! Information entered.";
}
else
{
?>
<form method="post" action="proInput.php">
Username:<input type="Text" name="username"><br>
Password:<input type="Text" name="password"><br>
<input type="Submit" name="submit" value="Register"></form>
<?
}
?>
Every time I type SELECT * FROM member; in MySQL my database is empty.
mysqli_commit($con);
mysqli_query($con,$sql);
mysqli_close($con);
You're committing before you insert, and then closing an uncommitted transaction. Try swapping the first two lines in the above excerpt.
As you answered already in your comment,
the name of the file isn't main_login.php but proinput.php
Your form is posting it's data to main_login.php and I'm assuming you don't have the insert query on that page, your code isn't run at all.
Options:
Try changing the name of this php file to main_login.php and then instead of the echo redirect the user to the login page
Move this part of the insert to your main_login.php
if(isset($_POST["submit"]))
{
$User = "";
$Password = "";
$Database = "member";
$Host = "localhost";
$con = mysqli_connect($Host, $User, $Password);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,$Database);
$myusername = $_POST["username"];
$mypassword = $_POST["password"];
$sql = "INSERT INTO member (username, password) VALUES ('$myusername','$mypassword')";
mysqli_query($con,$sql);
mysqli_commit($con);
mysqli_close($con);
echo "Thank You! Information entered.";
}
else
{
?>
for debugging add the following to the very top of your php file right after the opening of php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
This worked for me
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
if(isset($_POST["submit"]))
{
$User = "db_user";
$Password = "db_password";
$Database = "db_name";
$Host = "db_host";
$con = mysqli_connect($Host, $User, $Password);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,$Database);
$myusername = $_POST["username"];
$mypassword = $_POST["password"];
$sql = "INSERT INTO member (username, password) VALUES ('$myusername','$mypassword')";
mysqli_query($con,$sql);
mysqli_commit($con);
mysqli_close($con);
echo "Thank You! Information entered.";
}
else
{
?>
<form method="post" action="proinput.php">
Username:<input type="Text" name="username"><br>
Password:<input type="Text" name="password"><br>
<input type="Submit" name="submit" value="Register"></form>
<?php
}
?>
please add 'or die (mysqli_error())' at the end of your query and get the sql error report. That should tell you what is exactly wrong with sql . Php error reporting will only give php errors.
am trying to update the databse with the pubupdate.php file with the mentioned file but it is giving error Notice: Undefined index: user in C:\xampp\htdocs\Publication\form.php on line 3
Notice: Undefined index: pass in C:\xampp\htdocs\Publication\form.php on line 4. I don't know how this page is directed to form.php. However form.php has been used to create the account of the user so that user can login into the website. The login is done by the page login.php which is using the data which has been inserted in create.php. I don't know how to solve this problem and howcome pubupdate.php is directing to form.php and how to solve this problem.
I am posting the codes which I have used.
pubupdate.php
<?php
$typereg = $_POST['papertype'];
$ptitlereg = $_POST['ptitle'];
$fauthorreg = $_POST['firstauthor'];
$coauthorreg = $_POST['coauthor'];
$abstractreg = $_POST['abstract'];
$nameconreg = $_POST['namecon'];
$areareg = $_POST['area'];
$datereg = $_POST['date'];
$startpagereg = $_POST['startpage'];
$endpagereg = $_POST['endpage'];
$countryreg = $_POST['country'];
$taken = "false";
$database = "publication";
$password = "";
$username = "root";
$con = mysql_connect('localhost', $username, $password) or die("Unable to connect database");
#mysql_select_db($database, $con) or die("Unable to connect");
mysql_query("INSERT INTO `paper` VALUES('$typereg', '$ptitlereg','$fauthorreg','$coauthorreg','$abstractreg' ,'$nameconreg', '$areareg','$datereg', '$startpagereg', '$endpagereg', '$countryreg' )") or die("Strange Error");
echo "Account Created";
mysql_close($con);
header('Location: home.php');
?>
form.php
<?php
$userreg = $_POST['user'];
$passreg = $_POST['pass'];
$taken = "false";
$database = "publication";
$password = "";
$username = "root";
if($userreg && $passreg){
$con = mysql_connect('localhost', $username, $password) or die("Unalbe to connect database");
#mysql_select_db($database, $con) or die("Unalbe to connect");
mysql_query("INSERT INTO `users` VALUES('', '$userreg', '$passreg')") or die("Strange Error");
echo "Account Created";
mysql_close($con);
header("Location : index.html");
} else {
echo "You need to have both a username and password";
}
?>
create.php
<?php
$userreg = $_POST['user'];
$passreg = $_POST['pass'];
$fnamereg = $_POST['fname'];
$lnamereg = $_POST['lname'];
$desigreg = $_POST['designation'];
$taken = "false";
$database = "publication";
$password = "";
$username = "root";
if($userreg && $passreg){
$con = mysql_connect('localhost', $username, $password) or die("Unable to connect database");
#mysql_select_db($database, $con) or die("Unable to connect");
mysql_query("INSERT INTO `users` VALUES('', '$userreg','$passreg','$fnamereg','$lnamereg' ,'$desigreg')") or die("Strange Error");
echo "Account Created";
mysql_close($con);
header('Location: index.html');
} else {
echo "You need to have both a username and password";
}
?>
In your form where you use to get the inputs i.e., Username and Password.
You should give it a name
Something like
<input type='text' name='user'>
<input type='password' name='pass'>
It is clear that you didn't give the name field in your code.
Note :
In addition you can have your class or id according to your need.
Additional Note :
For Debugging, I would recommend you to deal such errors easily by checking whether the value exists..
You can do it easily by the below code
if (isset($_POST['user']))
{
echo 'Username value is - '.$_POST['user'];
}