I am working on PHP and MySQL environment for first time..
And I got another problem with my connectivity.
I am unable to create a connection between both of them.
I am trying to make a code for login page.
My database name and all those things are correct.
Here's my code..
<?php
$con = NULL;
if (empty($_POST['username']) || empty($_POST['password'])) {
$error="Username or Password is invalid";
}
else {
global $con;
$con=mysqli_connect("localhost","root","","student");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
$sql = "select * from login where password='" . $_POST['password'] . "' AND username='" . $_POST['username'] . "'";
echo $sql;
$query=mysqli_query($sql,$con);
$rows=mysqli_num_rows($query);
echo $rows;
if ($rows==1) {
$_SESSION['login_user'] = $_POST['username'];
//Initializing Session
header("location: /pages/profile.php"); //Redirecting to other page
} else {
$error = "Username or Password is invalid";
}
}
//SQL query to fetch information of registered users and finds user match.
//Closing Connection
mysql_close($con);
}
?>
Errors :
Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\pages\login.php on line 21
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\pages\login.php on line 24
Warning: mysql_close() expects parameter 1 to be resource, object given in C:\xampp\htdocs\pages\login.php on line 39
The first warning tells you exactly what's wrong:
Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\pages\login.php on line 21
Here you define your variables:
$con=mysqli_connect("localhost","root","","student");
// ...
$sql = "select * from login where password='" . $_POST['password'] . "' AND username='" . $_POST['username'] . "'";
So $con is a mysqli object and $sql is a string. Then you call the function:
$query=mysqli_query($sql,$con);
You're passing it the string and then the connection. The error says that the first object should be the connection. Like this:
$query=mysqli_query($con,$sql);
Also, and this is important... I realize you're just getting started and just learning the concepts. But make sure you understand this before writing any code which would be used in any live system or which would be responsible for any user's data. Your code is wide open to SQL injection attacks. Basically, any user has complete access to your database and probably you server. Please start by reading this.
What this code currently does, even though you may not be aware of it, is it executes user input as code. Clearly you don't want any user to be able to execute any arbitrary code they want on your server, but currently that's exactly what you're allowing. Again, you're new, so it's an understandable mistake. I'm not trying to blame you, just convince you of the importance of this. Especially when your websites start to contain user data.
Related
if(isset($_POST['submit'])){
$uname=$_POST['username'];
$pwd=$_POST['password'];
$acc_type=$_POST['acc_type'];
$_SESSION['user_type']=$acc_type;
if($acc_type=='Teacher'){
$sql="select userid,password from teacherinfo where userid='$uname'";
}
else if($acc_type=='Student'){
$sql="select userid,password from studentinfo where userid='$uname'";
}
else if($acc_type=='Admin'){
$sql="select userid,password from admininfo where userid='$uname'";
}
$query = mysql_query($sql);
$count = mysql_num_rows($query);
if($count>0){
$row_data = mysql_fetch_row($query);
if($row_data[1]==$pwd){
$_SESSION['userid']=$row_data[0];
$url="profile.php";
header("Location:$url");
}
else{
echo "Password Miss match!";
}
}
else{
echo "User not Found!";
}
}
Notice: Undefined variable: sql in C:\xampp\htdocs\MJ\index.php on line 39 Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\MJ\index.php on line 40
Looking at the code from the PHP website you are not linking your sql statement to the connection you made to your database. Look at the code below and you will see that a variable is create called $link this is then supplied the database to be used and then placed in as a second variable in the sql statement variable $result.
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
?>
You really do, as the comment state, need to stop using mysql and move over to PDO, this site should provide you with enough information to get your started and will secure the statements to the database - https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Further to this you also need to look at hashing your passwords, currently you are using plain text, this is not secure. Using something like password_hash() - http://php.net/manual/en/function.password-hash.php - would provide a much more secure way of storing passwords. Once they are stored securing you can use password_verify() to check them against supplied passwords in the future.
I am working on a login script with prepared statements in PHP procedural mysqli syntax. Here is my current code:
<?php
include "/ssincludes/functions.php";
$host = HOST;
$username = USER;
$password = PASSWORD;
$db_name = DATABASE;
$table = TABLEU;
//These includes and constants are fine I checked them all
$con = mysqli_connect($host, $username, $password, $db_name);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$myusername='test';
$mypassword='password1';
$sql="SELECT * FROM $table WHERE user_name=? and password=?";
$result=mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($result, 'ss', $myusername, $mypassword);
mysqli_execute($result);
mysqli_stmt_fetch($result);
$row_cnt = mysqli_num_rows($result);
echo $row_cnt;
?>
The error returned is: Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, object given
I thought I took out all instances of OO PHP in my script? Also I understand that this may mean my query is incorrect so I ran it on MySQL in the database and all seems to be fine there:
So I am lost as to what the problem could be. I read many similar posts (maybe I'm missing one that is exactly similar to mine) and none seem to handle the problem. I appreciate your time and help.
P.S. I understand the security issues with plain text passwords and using "password1". I plan to use better security practices as I build this but I just want to get prepared statements down first.
You should use
mysqli_stmt_execute
mysqli_stmt_num_rows
Instead of the mysqli_execute and mysqli_num_rows.
I have a a form that pulls data from a database(mysql to be specific) and echos the data into the value section of <input> tags. It doesn't seem to be working I have coded a view section of my website to do the same thing but from a different table in my database. I use the same code to make making changes easy and if another developer works on my site in the future. Anyway it doesn't seem to be working I'm not sure why though.
The full error I get:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/caseol5/public_html/jj/admin/news_update.php on line 9
Here is line 9 that the error is referring to:
$result = mysqli_query($link,$sql);
I know that both of those function are not null as I did:
echo $link
echo $sql
before that line after I started feting the error and they both are not null.
Here is the full code segment:
$nid = $_GET['nid'];
include ("../sql/dbConnect.php");
$sql = "SELECT * FROM jj_news WHERE news_id = $nid";
echo "<p>The SQL Command: $sql </p>";
echo "<p>Link: $link </p>";
$result = mysqli_query($link,$sql);
if (!$result)
{
echo "<h1>You have encountered a problem with the update.</h1>";
die( "<h2>" . mysqli_error($link) . "</h2>") ;
}
$row = mysqli_fetch_array($result);
$ntitle = $row['news_title'];
$ntline = $row['news_titleline'];
$ndesc = $row['news_desc'];
$nother = $row['news_other'];
I have looked into mysqli_query and I can't find anything I'm missing. I have also tired breaking the code down (and running parts of it and it gives the same error. My guess is it something small that I missed. I've looked at other question on this site that do that are a little similar but none seem to help. I've been looking at this for a while now and need another pair of eyes.
Update
As requested the contents of my dbconnect.php file:
$hostname = "localhost";
$username = "caseol5_jjoes";
$database = "caseol5_jj_site";
$password = "password1";
$link = mysqli_connect($hostname, $username, $password, $database);
$link = mysqli_connect($hostname,$username,$password,$database) or die("Error " . mysqli_error($link));
if (!$link)
{
echo "We have a problem!";
}
As clearly stated in the error message, mysqli_querydocs expects the first parameter to be a mysqli resource. In your case, this parameter is called $link but it holds a null value. A proper mysqli resource is normally obtained from connecting with the database by making use of mysqli_connectdocs
I expect the ../sql/dbConnect.php file holds the logic to connect with the database. Verify whether the $link variable is indeed initialized there. If it's not there, try to find an occurrence of mysqli_connect - maybe the resource is set to a different variable.
Without knowing what exactly is in ../sql/dbConnect.php, your problem right now is that you do not have a valid mysqli resource to use for mysqli_query.
although this question has been asked (and answered) many times, I didn't find a solution to the problem.
Here is my code:
<?php
#session_start();
include("./include/config.php");
include("./include/db_connect.php");
include("functions.php");
if (!isset($_GET['artikelID'])){$_GET['artikelID'] = "";}
if (!isset($_SESSION['UserID'])){$_SESSION['UserID'] = "";}
$sql = "SELECT kundenID FROM kunden WHERE username = '".$_POST['myusername']."' AND password = '".md5($_POST['mypassword'])."' ";
$result = mysqli_query($connect, $sql) OR die("<pre>\n".$sql."</pre>\n".mysqli_connect_error()); // this is line 13
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result)==1){
doLogin($row['kundenID'], isset($_POST['Autologin']));
header("location:cart.php?action=add&artikelID=".$_GET['artikelID']."&id=". $_SESSION['UserID'] ." ");
}
else {
header("location:k_login.php?error=TRUE ");
}
include("./include/db_close.php");
?>
mysqli_connect_error() shows me the absolute correct sql-query; the sql-query is tested with a tool named mysql-front and brings exactly one (and the correct one) result, which is 'kundenID'.
I have tested many things (like $_SESSION['connect'] or $_GLOBALS['connect'] instead of $connect in db_connect.db), but with no result.
Can anyone please help me?
-- Update --
Why does nobody answer?
Is the description of the problem unclear?
The db-connection is established like this:
<?php
error_reporting(E_ALL);
$connect = mysqli_connect($dbserver,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno()){
echo "Zeile ".__LINE__.": Datenbankverbindung ist fehlgeschlagen ! " . mysqli_connect_error();
exit();
}
?>
All the db-variables are known in the checklogin-script (tested). All the $_POST-variables are also known in the checklogin-script (tested). I even tried a hard-coded sql-query (with the real data of the test-record in the db).
The result is still the same: mysqli_connect_error() reports the correct query - but then nothing more happens.
I have spent more than 10 hours in the meantime. I really would appreciate, if someone could help me.
Couldn't fetch mysqli means that PHP is unable to identify the contents of your $connect variable as a valid mysqli connection. Try adding some error handling into "./include/db_connect.php" to get an idea of what happened to the mysqli connection that is preventing you from using it.
I've got a pretty standard call to a MySQL database and for some reason I can't get the code to work. Here's what I have:
$mysqli = mysqli_connect("localhost","username","password");
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
session_start();
$sql = "SELECT * FROM jobs ORDER BY id DESC";
$result = $mysqli->query($sql);
$num_rows = mysqli_num_rows($result);
Now, first, I know that it is connecting properly because I'm not getting the die method plus I added an else conditional in there previously and it checked out. Then the page displays but I get the errors:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in blablabla/index.php on line 11
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in blablabla/index.php on line 12
I've double-checked my database and there is a table called jobs with a row of "id" (it's the primary row). The thing that confuses me is this is code that I literally copied and pasted from another site I built and for some reason the code doesn't work on this one (I obviously copy and pasted it and then just changed the table name and rows accordingly).
I saw the error and tried:
$num_rows = $mysqli_result->num_rows;
$row_array = $mysqli_result->fetch_array;
and that fixed the errors but resulted in no data being passed (because obviously $mysqli_result has no value). I don't know why the error is calling for that (is it a difference in version of MySQL or PHP from the other site)?
Can someone help me track down the problem? Thanks so much. Sorry if it's something super simple that I'm overlooking, I've been at it for a while.
You didn't selected the database
$mysqli = mysqli_connect("localhost","username","password","database");
The problem is you haven't selected the database.
use this code for select database.
$mysqli = mysqli_connect("localhost","username","password");
mysqli_select_db("db_name",$mysqli);
You have to select database in order to fire mysql queries otherwise it will give you error.
I believe that schtever is correct, I do not think you are selecting the database. It isn't in the code snip and if you search online you see other people with similar errors and it was because the database wasn't selected. Please let us know if you selected a database before anything else is checked. Thanks.
Try this:
session_start();
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
$mysqli->close();
}
$query ="SELECT * FROM jobs ORDER BY id DESC";
$values = $mysqli->query($query);
if($values->num_rows != 0)
{
while($row = $values->fetch_assoc())
{
//your results echo here
}
}
else
{
//if no results say so here
}
See this manual for mysqli_connect you can select the database right in this function.