Object returned on mysql_num_rows() function - php

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.

Related

Get a data in a database?

I would like to get the registered IP of a user in my database.
I use this method :
$securityRes=mysql_query("SELECT * FROM security WHERE userName=".$userRow['name']);
$securityRow=mysql_fetch_array($securityRes);
But it return me nothing, when I use this code :
echo $securityRow['IP']
I'm blocked on it since like 1 hours, and Google seems to don't want to be my friend today :/
So I ask help here, hoping I will get some.
Thank you in advance; cordially, Matt.
PS - Here is my database | my table "security" :
First of all use mysqli_* instead of mysql_*. And the issue is here:
"SELECT * FROM security WHERE userName=".$userRow['name'];
name is always a string, and for string comparison you have to bind the value in single quotes like:
"SELECT * FROM security WHERE userName='".$userRow['name']."'";
You should try debugging here.
$securityRes = mysql_query("SELECT * FROM security WHERE userName=".$userRow['name']) or die(mysql_error());
$securityRow = mysql_fetch_array($securityRes);
echo "<pre>";
print_r($securityRow); // Check your result
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
1) In your code you need string to be enclosed by single quotes.
2) Try to use prepared statement or PDO like this
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //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");
$stmt = $conn->prepare("SELECT * FROM security WHERE userName=?");
$stmt->bind_param('s',$userRow['name']);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt->execute();
$get_result =$stmt->get_result();
$row_count= $get_result->num_rows;
if($row_count>0)
{
print_r($get_result->fetch_assoc());
}

mysqli_error() expects parameter 1 to be mysqli, null given

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.

Updating mysql database with php using variables

I am having problems updating mysql with php using varables.
mysqli_query($connection, "UPDATE passwords SET used=1, time_used='{$time}'
WHERE password='{$key}'
");
I was given the error:
Warning: mysqli_query() expects parameter 1 to be mysqli, resource given in C:\wamp\www\key_check.php on line 47
any ideas why?
Thanks!
EDIT: Whole Code: http://pastebin.com/raw.php?i=W5cx8pBP
The "new mysqli" solution seems to be giving problems when trying to
$result = mysql_query("SELECT * FROM passwords", $connection);
Thanks :)
Your connection setting must look like
$connection = new mysqli($host,$username,$pass,$db);
Then execute the query using your way or by this way also
$query="UPDATE passwords SET used=1, time_used='{$time}'
WHERE password='{$key}'
";
$stmt = $connection->query($sql);
note: using prepared statements for mysqli can also possible and great. By somehow you also needed to bind parameters in there..
You have to declare $connection by creating a new mysqli object. If you fail to do so, you can check the documentation for mysqli constructor
Here's the code from the documentation.
$connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($connection->connect_error) {
die('Connect Error (' . $connection->connect_errno . ') '
. $connection->connect_error);

PHP mysql query syntax errors

I'm fairly new to PHP/MySQL and I seem to be having a newbie issue.
The following code keeps throwing me errors no matter what I change, and I have a feeling it's got to be somewhere in the syntax that I'm messing up with. It all worked at home 'localhost' but now that I'm trying to host it online it seems to be much more temperamental with spaces and whatnot.
It's a simple login system, problem code is as follows:
<?php
session_start();
require 'connect.php';
echo "Test";
//Hash passwords using MD5 hash (32bit string).
$username=($_POST['username']);
$password=MD5($_POST['password']);
//Get required information from admin_logins table
$sql=mysql_query("SELECT * FROM admin_logins WHERE Username='$username' ");
$row=mysql_fetch_array($sql);
//Check that entered username is valid by checking returned UserID
if($row['UserID'] === NULL){
header("Location: ../adminlogin.php?errCode=UserFail");
}
//Where username is correct, check corresponding password
else if ($row['UserID'] != NULL && $row['Password'] != $password){
header("Location: ../adminlogin.php?errCode=PassFail");
}
else{
$_SESSION['isAdmin'] = true;
header("Location: ../admincontrols.php");
}
mysql_close($con);
?>
The test is just in there, so I know why the page is throwing an error, which is:
`Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in 'THISPAGE' on line 12`
It seems to dislike my SQL query.
Any help is much appreciated.
EDIT:
connect.php page is:
<?php
$con = mysql_connect("localhost","username","password");
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
?>
and yes it is mysql_*, LOL, I'll get to fix that too.
You should escape column name username using backtick, try
SELECT *
FROM admin_logins
WHERE `Username` = '$username'
You're code is prone to SQL Injection. Use PDO or MYSQLI
Example of using PDO extension:
<?php
$stmt = $dbh->prepare("SELECT * FROM admin_logins WHERE `Username` = ?");
$stmt->bindParam(1, $username);
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
Sean, you have to use dots around your variable, like this:
$sql = mysql_query("SELECT * FROM admin_logins WHERE Username = '". mysql_real_escape_string($username)."' ");
If you use your code just like this then it's vulnerable for SQL Injection. I would strongly recommend using mysql_real_escape_string as you insert data into your database to prevent SQL injections, as a quick solution or better use PDO or MySQLi.
Besides if you use mysql_* to connect to your database, then I'd recommend reading the PHP manual chapter on the mysql_* functions,
where they point out, that this extension is not recommended for writing new code. Instead, they say, you should use either the MySQLi or PDO_MySQL extension.
EDITED:
I also checked your mysql_connect and found a weird regularity which is - if you use " on mysql_connect arguments, then it fails to connect and in my case, when I was testing it for you, it happened just described way, so, please try this instead:
$con = mysql_connect('localhost','username','password');
Try to replace " to ' as it's shown in the PHP Manual examples and it will work, I think!
If it still doesn't work just print $row, with print_r($row); right after $sql=mysql_query() and see what you have on $row array or variable.

Warning: mysqli_error() expects exactly 1 parameter, 0 given [duplicate]

This question already has answers here:
Warning: mysqli_error() expects exactly 1 parameter, 0 given error
(4 answers)
Closed 4 years ago.
When trying to return a simple set of results from my database table 'checklist' I receive the following error;
"Warning: mysqli_error() expects exactly 1 parameter, 0 given"
The code of my list.php file is as follows;
<?php
require_once('/includes/connection.inc.php');
// create database connection
$conn = dbConnect('read');
$sql = 'SELECT * FROM checklist ORDER BY created DESC';
$result = $conn->query($sql) or die(mysqli_error());
?>
<?php while($row = $result->fetch_assoc()) { ?>
<?php echo $row['created']; ?>
<?php echo $row['title']; ?>
<?php } ?>
The contents of my connection.inc.php file (for reference) is as follows;
<?php
function dbConnect($usertype, $connectionType = 'mysqli') {
$db = 'projectmanager';
$host = 'localhost';
if ($usertype == 'read') {
$user = 'root';
$pwd = '';
} elseif ($usertype == 'write') {
$user = 'root';
$pwd = '';
} else {
exit('Unrecognized connection type');
}
// Connection goes here...
if ($connectionType == 'mysqli') {
return new mysqli($host, $user, $pwd, $db);
} elseif ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
}
?>
I've been trying to follow some examples out of a book PHP Solutions: Dynamic Web Design Made Easy found HERE ...but I already had an issue with the connection.inc.php file (snippet shown above) where I had to correct "or die ('Cannot open database');" and replace it with the IF based statement you see above for the mysqli_error. So I am wondering if this book is riddled with some basic, fundamental errors - at least that when presented to novices like me leave us baffled.
Any help guys?
Thank you
I think the problem you're having is because you're combining object-oriented and non-OO calls to the MySQLi library.
The mysqli_error() function does indeed require a parameter -- it requires the connection variable; in your case, $conn.
mysqli_error($conn)
Howwever, if you'd written it in an OO manner, as you have done for most of the rest of the database calls, you would have written it like this:
$conn->error
Since all the rest of your code is written using object-oriented calls, it would make sense to use it for this call as well.
So your full line of code would look like this:
$result = $conn->query($sql) or die($conn->error);
You can see further examples in the PHP manual: http://php.net/manual/en/mysqli.error.php
Hope that helps.
With regard your question about the book you're using: I can't comment directly on the book itself as I haven't read it. But note that there are two MySQL libraries for PHP; the older mysql library, and the newer mysqli library. The older library also has a mysql_error() function, which differs from the newer one in that it does not require a connection variable. If there is an error in the book you are using, this may be the source of the confusion.

Categories