I'm trying to switch my website over to MySQLi and I'm following the W3schools MySQLi guide to do so. I've hit a roadblock, though. I have a function to check if a specified user is an admin on the site. I've put echo in various spots to find where the issue is, and I've figured out that it most likely doesn't see the user. $username is set to the variable $user. Here's the whole code block (part of connect.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lark";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
session_start();
if(!isset($_SESSION["user_login"])) {
$user = "";
} else {
$user = $_SESSION["user_login"];
}
//functions
function isAdmin($username) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lark";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_get_is_admin = "SELECT * FROM users WHERE username='$username' LIMIT 1";
$get_is_admin = mysqli_query($conn, $sql_get_is_admin);
if(mysqli_num_rows($get_is_admin) > 0) {
echo "num_rows";
while ($row = mysqli_fetch_assoc($get_is_admin)) {
$is_admin_bool = $row['admin'];
echo "while";
if($is_admin_bool == 0){
return false;
} elseif ($is_admin_bool == 1) {
return true;
}
}
} else {
echo "not found.";
}
}
?>
Here's the code I used to test the $user variable:
<?php
include("connect.php");
?>
<div class="main">
<h1>Welcome back, <?php echo $user; ?></h1>
foo
<?php
/*if(isAdmin($user) == true) {
echo "<div style='display: table-cell;' class='rightcell'>
<h3 style='color: #000;'>Admin Tools</h3>
<a href='userlist.php' target='_blank'>Userlist</a>
</div>";
} else {
} */
echo isAdmin($user);
?>
</div>
I also had to reconnect to the database or else I'd get this error on the site:
Notice: Undefined variable: conn in C:\xampp\htdocs\lark\connect.php on line 33
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\lark\connect.php on line 33
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\lark\connect.php on line 35 not found.
If I fix it so there's no error, it just says "not found."
the $conn variable is not defined in your function, example:
function isAdmin($username) {
global $conn;
..................
}
You don't have $conn in your function, it is commented out.
function isAdmin($username) {
/*$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lark";
$conn = mysqli_connect($servername, $username, $password, $dbname);*/
Related
Connection failed: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known.
( ! ) Fatal error: Uncaught Error: Call to a member function prepare() on string in C:\wamp\www\websits\admin\validate.php on line 17
( ! ) Error: Call to a member function prepare() on string in C:\wamp\www\websits\admin\validate.php on line 17
Code-
<?php
include_once('connection.php');
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"]== "POST") {
$adminname = test_input($_POST["adminname"]);
$password = test_input($_POST["password"]);
$stmt = $conn->prepare("SELECT * FROM adminlogin");
$stmt->execute();
$users = $stmt->fetchAll();
foreach($users as $user) {
if(($user['adminname'] == $adminname) &&
($user['password'] == $password)) {
header("Location: adminpage.php");
}
else {
echo "<script language='javascript'>";
echo "alert('WRONG INFORMATION')";
echo "</script>";
die();
}
}
}
?>
// Connection -
<?php
$conn= "";
try {
$servername = "localhost:3306";
$dbname = "website";
$username = "root";
$password = "";
$conn = new PDO("mysql:host=$servername and dbname=website",$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Check Your connection.php file is it in the same directory where validate.php file is if not them provide the correct path, else your prepare statement is correct.
Where is you Connection file is can you share the path of of connection.php and validate.php path.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_db_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Your connection string is wrong
Your string
$conn = new PDO("mysql:host=$servername and dbname=website",$username, $password);
Should be
$conn = new PDO("mysql:host={$servername};dbname={$dbname}",$username, $password);
And your servername should be without a port
$servername = "localhost";
Please see
https://www.php.net/manual/en/pdo.connections.php
Alter your connection.php code as follows,
$username = 'root';
$password = '';
$conn = new PDO('mysql:host=localhost;dbname=website',$db_username,$db_password );
if(!$conn){
die("Fatal Error: Connection Failed!");
}
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";
}
?>
Im trying to do if else using Camp data in table testing_data. did i do this correctly in retrieve the data and calling it in if else..i really newbies in php ..hope you can help me..tq
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "brindley";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM testing_data";
$result = $conn->query($sql);
$user = mysqli_fetch_array($result);
if($user["t_month"] === 'Q1')
{
if($user['t_bbq'] === 'Kambing Golek')
{
if($user['t_participant'] =='>=21 to <=40')
{
if($user['t_outdoor'] == 'Tiada')
{
if($user['t_packages']== 'Pakej 4')
{
echo "YES, People prefer choose packages like this";
}
else
{
echo "NO";
}
}
}
}
?>
I am building a login portal with mySQL and PHP
I have this file (dbc.php):
<?php
class db_connect {
protected $DB_SERVER = "localhost";
protected $DB_USERNAME = "root";
protected $DB_PASSWORD = "";
protected $DB_DATABASE = "mydb";
public function connect() {
$conn = new mysqli($this->DB_SERVER, $this->DB_USERNAME, $this->DB_PASSWORD, $this->DB_DATABASE);
if(mysqli_connect_errno()) {
die("Connection failed: ". mysqli_connect_errno());
}
return $conn;
}
}
?>
Then my actual PHP script (login.php) takes a POST from the login page:
<?php
//include database connection
include("dbc.php");
session_start();
//put post values into variables
$username = $_POST['username'];
$password = $_POST['password'];
//create db connector object
$db = new db_connect();
$conn = $db->connect();
//select correct db
mysqli_select_db($conn,”mydb”);
$username = mysqli_real_escape_string($conn,$username);
$query = "SELECT password FROM mydb.users WHERE username = '$username'";
$result = mysqli_query($conn,$query);
if(mysqli_num_rows($result) == 0)
{
header('Location: sorry.html');
}
$pwhash = $result;
if (password_verify($password, $pwhash)) {
header('Location: welcome.php');
} else {
header('Location: sorry.html');
}
?>
This never returns a value which is odd.
Any help appreciated!
$result holds a MySQLi response resource, not a string or array.
You need to change this line:
$pwhash = $result;
To this:
$pwhash = mysqli_fetch_assoc($result)['password'];
I am learning as i go and been picking up snippets of code as i go and been working on this for the past few days and now i have thrown the towel in to seek help.
I am trying to calculate the sum of 2 columns in my database using PDO.
here is my code
<?php
$host = "localhost";
$db_name = "dbname";
$username = "root";
$password = "root";
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}
// show error
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$query = "SELECT SUM (fill_up) AS TotalFill,
SUM (mileage_covered) AS Totalmiles
FROM fuel_cost";
$row = $query->fetch(PDO::FETCH_ASSOC);
$total_fill = $row['TotalFill'];
$total_miles = $row['Totalmiles'];
$myanswer = $total_fill/$total_miles;
//display the answer
echo $myanswer
?>
I have also checked my database table and both columns are varchar(32)
the error I am getting is Call to a member function fetch() on a non-object
I have searched into this but not sure what's the issue with the above code
Thank You in advance
Try this code :-
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT SUM (fill_up) AS TotalFill,
SUM (mileage_covered) AS Totalmiles
FROM fuel_cost";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$total_fill = $row['TotalFill'];
$total_miles = $row['Totalmiles'];
$myanswer = $total_fill / $total_miles;
//display the answer
echo $myanswer;
die;
}
} else {
echo "0 results";
}
$conn->close();
?>