I am getting the error:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home/mjcrawle/public_html/home/index.php on line 23
Line 23 turns out to be $num_results = mysqli_num_rows($result); but I am thinking the error is further up but I am having trouble finding it.
The actual code that I am using to connect to the DB is (I do understand there is a redundancy if the database cannot connect):
Any help would be wonderful and a reason for the error would be awesome!
/*Connect To DB*/
$conn = mysqli_connect($host, $user, $pwd)
or die("Could not connect: " . mysql_error()); //connect to server
mysqli_select_db($conn, $database)
or die("Error: Could not connect to the database: " . mysql_error());
/*Check for Connection*/
if(mysqli_connect_errno()){
/*Display Error message if fails*/
echo 'Error, could not connect to the database please try again later.';
exit();
}
/* Query for states */
$query = "SELECT StateAbbreviation, StateName, FROM USState ORDER BY StateName";
$result = mysqli_query($conn, $query);
$num_results = mysqli_num_rows($result);
?>
You have an extra comma before the FROM in query = "SELECT StateAbbreviation, StateName, FROM USState ORDER BY StateName";, you may be getting an error and not having a result when you execute the query.
If the query fails, mysqli_query returns boolean false
After $result = mysqli_query($conn, $query);, you should test the return value before continuing:
if ( ! $result){
$error = mysqli_error($conn);
//do something with the error message
}
See EmCo's answer for why your query is failing.
<?php
$con=mysqli_connect('localhost','root','','dbname') or die ("Connection Failed");
?>
This is the simple method of DB Connection
Related
i'm in a middle of making a query with my new database and i keep getting the message (Database query failed) through the code below:
<?php
//create a database connection
$dbhost= "localhost";
$dbname= "widget_corp";
$connection=mysqli_connect($dbhost , $dbname);
if(mysqli_connect_errno()){
die("Database connection failed :" . mysqli_connect_error ."(". mysqli_connect_errno .")");
}
?>
<?php
//perform a database query
$query = "SELECT * FROM subjects";
$result = mysqli_query($connection ,$query);
if (!$result){
die("Database query failed.");
}
?>
please advise
You aren't passing in a username or password. mysqli_connect() requires four parameters to be passed in : http://php.net/manual/en/function.mysqli-connect.php
You're only passing in a host and database name.
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I need a little help again... I get error mysql parameters, I know the problem but I cant find the missing parameters... this is the problem line
**`$result_template = mysqli_query($select_template) or die(mysql_error());`**
I know 1 parameter is missing but I dont know whichone?? Can you pls help me? Thanks
This is part of the codes maybe usefull....
/*function to display the active template*/
function displayTemplate(){
$tableprefix = "";
global $tableprefix,$_SESSION;
$template_array = array();
$select_template = "SELECT vtop_filename,vleft_filename,vbottom_filename,vimages_folder,vcss_name,vtemplate_name
FROM ".$tableprefix."template_master WHERE vactive_status = 'Y'";
1579---->>>> $result_template = mysqli_query($select_template) or die(mysql_error());
$template_row = mysql_fetch_assoc($result_template);
array_push($template_array,$template_row['vtop_filename'],$template_row['vleft_filename'],$template_row['vbottom_filename'],$template_row['vimages_folder'],$template_row['vcss_name'],$template_row['vtemplate_name']);
return $template_array;
}
You need to tell it where to connect to. Here is a simple example of working code to connect to a database from PHP.
<php
//Connect to DB
$conn = new mysqli("Hostname","Username","Password","Database");
//If the connection has errors
if ($conn->connect_error){
//Display the error
die("Connection failed because: " . $conn->connect_error);
}
//Otherwise the connection is good so lets create a sql query
$sql = "SELECT * FROM Database";
//Get the results of the query
$result = $conn->query($sql);
You should refer the php documentation for this here
As you are using the procedural style, so you will have to pass the mysqli_connect resource to your mysqli_query
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Create table doesn't return a resultset */
if (mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT)) {
/* Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error */
if (!mysqli_query($link, "SET #a:='this will not work'")) {
printf("Error: %s\n", mysqli_error($link));
}
mysqli_free_result($result);
}
mysqli_close($link);
?>
but as I can see that you are using it in some function so pass an object of db to this function and then use it in your mysqli_query
I used
mysqli_connect("infos in here");
at the top of my page, and tried to use
mysqli_query("INSERT INTO and other info here");
When I do that, I get this error:
Warning: mysqli_query() expects at least 2 parameters, 1 given in (...)
But if I instead use
$con = mysqli_connect("infos in here");,
$mysqli_query($con,"INSERT INTO and other info here");
The error goes away, and my script works.
My problem is that I need to use mysqli_query two different times in my page, and I don't want to open the connection again when it's already open.
How can I handle this?
Thanks.
My problem is that I need to use mysqli_query two different times in
my page, and I don't want to open the connection again when it's
already open.
How is it a problem ? open once query as many times then close the connection, example:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
mysqli_query($con,"SELECT * FROM Persons");
//one more
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
mysqli_close($con);
?>
No need to connect two times. An example here..
$con = mysqli_connect("host", "user", "password", "db");
if(mysqli_connect_errno()){
die(mysqli_connect_error());
}
//Query one
$result1 = mysqli_query($con, 'Query String');
//Query Two
$result2 = mysqli_query($con, 'Query String'); //Used same $con variable
//After finishing all queries
mysqli_close($con);
If you need to select multiple database then
$con = mysqli_connect("host", "user", "password");
//for DB bd_name1
mysqli_select_db($con, 'bd_name1');
$result1 = mysqli_query($con, 'Query String');
//for DB bd_name2
mysqli_select_db($con, 'bd_name2');
$result2 = mysqli_query($con, 'Query String');
But not connect frequent time.
Putting aside the SQL Injection and other security issues I am having a problem trying to get the following piece of code to work. I know I am close but cannot figure out how to do it. Currently I am receiving this error message:
"Successful Connection
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\proper\checklogin.php on line 30
wrong username/password"
Checklogin.php
<?php
session_start();
// Connect to server and select databse.
$conn= mysqli_connect("localhost", "root", "")
or die ('No connection');
print "Successful Connection";
mysqli_select_db($conn , 'ssssg3') or die ('database will not open');
// username and password sent from form
$email=$_POST['email'];
$password=$_POST['password'];
$sql = "SELECT * FROM log_in_info where email=$email";
$result=mysqli_query($conn, $sql);
$row=mysqli_fetch_array($result);
if ($row['password'] == $password) {
header('location:main1.php');
}
else
{
echo 'wrong username/password';
}
?>
$sql = "SELECT * FROM log_in_info where email=$email";
This is where your error rests. Try:
$sql = "SELECT * FROM log_in_info where email='$email'";
The query fails, because you need to put literals into ' '.
Be sure to check the return value of mysqli_query and use mysqli_error to determine the actual error message.
To do some proper error checking I suggest (assuming that $email is properly escaped)
$sql = "SELECT * FROM log_in_info where email='$email'";
if(!$sql) die(mysqli_error($conn));
Notice, it's not Error message. "Undefined index: password" means, what you accessing array key, what not exists. To avoid id you can use some like this (for you code):
if (array_key_exists( 'password', $row ) and $row['password'] === $password) {
I have databases of users and each has tables. I want to loop through each user and find the number of rows of a particular table common to each. So i connect to the first DB(usersDB) and pick the names of other DB's from a table(userinfo) row(user_name). I then connect to each DB using the names obtained in userinfo and try to find the number of rows they each have on a particular table(products) common to them. I tried this but shows the same number of rows for all of them. Any help??
<?php
//db parameters
$dbhost = "localhost";
$dbname = "usersDB";
$dbuser = "root";
$dbpass = "";
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
//select main db
$query = "SELECT user_name FROM userinfo";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_BOTH))
{
$dbName =$row['user_name'];
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db("dbprefix_".$bName) or die("MySQL Error: " . mysql_error());
// do a query for each db
$query = mysql_query('SELECT * FROM `products`');
$num_rows = mysql_num_rows($query);
echo $dbName." has".$num_rows."products"."<br/>";
}
?>
I think problem is in following line
mysql_select_db("dbprefix_".$bName) or die("MySQL Error: " . mysql_error());
I think this line will be
mysql_select_db("dbprefix_".$dbName) or die("MySQL Error: " . mysql_error());
this may not be your issue but I noticed you arn't closing the connection to each database after you query from it. you should assign a variable to mysql_select_db and after you echo close the database like this:
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
while($row = mysql_fetch_array($result, MYSQL_BOTH)){
$dbName =$row['user_name'];
$db = mysql_select_db("dbprefix_".$dbName, $conn) or die("MySQL Error: " . mysql_error());
if( $db ){
// do a query for each db
$query = mysql_query('SELECT * FROM `products`');
$num_rows = mysql_num_rows($query);
echo $dbName." has".$num_rows."products"."<br/>";
mysql_close( $db );
}
}
also notice I took the mysql_connect() line out of the while loop because you don't need to call this more than once. and I added the $conn variable for your mysql_connect() command, this way you can use $conn in your mysql_select_db() statement. This tell the select_db statement which connection to look in for this database (just alittle more secure).
Seems that there is a typo here:
mysql_select_db("dbprefix_".$bName) or die("MySQL Error: " . mysql_error());
Did you mean "dbprefix_".$dbName instead of $bName?
You don't need to call
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
every time, just call mysql_select_db for each database and PHP will reuse the connection
This is a copy paste from php manual may be it helps you
If you use implode() with the return value by mysql_fetch_array,
if you use MYSQL_BOTH on parameter 2, the result is not really what you're expecting.
For example :
my sql database contains "Amine, Sarah, Mohamed";
$array = mysql_fetch_array($resource,MYSQL_BOTH);
or $array = mysql_fetch_array($resource);
echo implode(" - ", $array);
the result is : Amine-Amine-Sarah-Sarah-Mohamed-Mohamed
and we expect just : Amine-Sarah-Mohamed
You must use MYSQL_NUM or MYSQL_ASSOC on parameter 2 to resolve the problem.
Seems rather inefficient to start up a new connection, using the same user/password for every user you've got. MySQL is perfectly capable of querying across different databases from the same connection:
mysql_connect(...);
$sql = "SELECT user_name FROM userinfo";
$result = mysql_query($sql) or die(mysql_error()) {
while($row = mysql_fetch_assoc($result)) {
$username = $row['user_name'];
$sql2 = "SELECT count(*) AS cnt FROM dbprefix_{$username}.products";
$result2 = mysql_query($sql2) or (die(mysql_error());
echo "$username has {$result2['cnt']} products";
}
In short, doing
SELECT somedb.sometable.somefield
is the same as doing
mysql_select_db('somedb');
SELECT sometable.somefield;