Finding the number of rows of each user in MYSQL - php

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;

Related

Simple and effective way to echo the result of a query in PHP?

I'm new to MySQL and PHP and I m struggling to echo my queries (the results not the text!)
I have searched for this but nothing seems to work properly, the best I managed to do was echoing the text of the query. I might have some fatal mistakes but here is my code:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("atoma",$dbhandle)
or die("Could not select atoma");
$sql1 = mysql_query("SELECT (MAX(GRADE)) as maximum FROM thema3");
$r = mysql_fetch_array($sql1); // will return the result
echo $r['maximum'];
$sql2 = "SELECT COUNT(DISTINCT NAME) FROM thema2";
$sql1 = "SELECT AVG(GRADE) FROM thema3";
mysql_close($dbhandle);
?>
I get nothing as a result.
I have these 3 queries and all I want is just to print their results. I've written code for echoing only one of the 3 since the other 2 will be echoed as the first one I want to believe.
Your code seems incorrect because, the connection is mysqli and fetching is using mysql
$conn = new mysqli($servername, $username, $password, $dbname);
....
$sql1 = mysql_query("SELECT (MAX(GRADE)) as maximum FROM thema3");
$r = mysql_fetch_array($sql1); // will return the result
A full example of W3Schools
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
http://www.w3schools.com/php/php_mysql_select.asp
When you use max, avg, etc you pull only one result, so with the $result[0] you has the result you want
Edit:
If you're new, maybe you come to see read this:
http://codular.com/php-mysqli
So A) would leave using an outdated way to call the database, and B) with this in principle bringing the first row you would have the result of AVG, MAX, etc. when only one row which returns you if you make this types of sentences ;)

Select from Database errors [duplicate]

This question already has answers here:
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given
(2 answers)
Closed 1 year ago.
I want to select some info from my database called Catalogonline and display it on a Html Page.But now my php code show this errors
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in
C:\wamp\www\insert12.php on line 14
And
Warning: mysqli_query() expects parameter 1 to be mysqli, string given
in C:\wamp\www\insert12.php on line 15
And
Warning: mysqli_error() expects exactly 1 parameter, 0 given in
C:\wamp\www\insert12.php on line 18 Could not get data:
My code is
<?php
$dbhost = 'localhost';
$dbuser = 'Florin';
$dbpass = '######';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
$sql = 'SELECT id, Username,
Signup_Date, E-mail
FROM membri';
mysqli_select_db('catalogonline');
$retval = mysqli_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysqli_error());
}
while($row = mysqli_fetch_array($retval, MYSQL_ASSOC))
{
echo "Tutorial ID :{$row['id']} <br> ".
"Title: {$row['Username']} <br> ".
"Author: {$row['Signup_Date']} <br> ".
"Submission Date : {$row['E-mail']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysqli_close($conn);
?>
mysql_select_db expects two params, but you`re passing only one.
The correct use is:
mysqli_select_db(connection,dbname);
try to change to
mysqli_select_db($conn,'catalogonline');
In
mysqli_query( $sql, $conn );
try to change to:
mysqli_query( $conn, $sql );
In
mysqli_error();
try to change to:
mysqli_error($conn);
These problems are happening, because when you're using mysqli commands, you must pass the connection object (in your case $conn), so it will be able to identify in what connection you'll execute the commands.
There are a few things wrong with your code. This being a late answer, am submitting the following, indicating what is actually going on.
mysqli_select_db('catalogonline'); - it requires DB connection to be passed as the first parameter.
mysqli_select_db($conn, 'catalogonline');
http://php.net/manual/en/mysqli.select-db.php
or simply use all four parameters right away:
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $db);
http://php.net/manual/en/function.mysqli-connect.php
Then these parameters' variables in your query mysqli_query( $sql, $conn ) are inversed.
The connection comes first mysqli_query( $conn, $sql )
http://php.net/manual/en/mysqli.query.php
MYSQL_ASSOC that needs to be MYSQLI_ASSOC with the added I. You cannot mix mysql_ and mysqli_ functions together.
mysqli_error() requires connection be passed mysqli_error($conn)
http://php.net/manual/en/mysqli.error.php
string mysqli_error ( mysqli $link )
Then in your query, the E-mail column. MySQL is interpreting that as "E minus mail", thinking you want it to do math. It should either be wrapped in ticks, or rename it to either using an underscore E_mail or in one word Email.
<?php
$dbhost = 'localhost';
$dbuser = 'Florin';
$dbpass = 'atestat';
$db = 'catalogonline';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $db);
if(! $conn )
{
die('Could not connect: ' . mysqli_error($conn));
}
$sql = 'SELECT id, Username,
Signup_Date, `E-mail`
FROM membri';
$retval = mysqli_query( $conn, $sql );
if(! $retval )
{
die('Could not get data: ' . mysqli_error($conn));
}
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC))
{
echo "Tutorial ID :{$row['id']} <br> ".
"Title: {$row['Username']} <br> ".
"Author: {$row['Signup_Date']} <br> ".
"Submission Date : {$row['E-mail']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysqli_close($conn);
?>

sql query with left join in php don't work

I made a SQL query in my database and it works perfectly, but when I try to put this same query into PHP, it doesn't work. I cannot figure out where is the error.
//connection variables
$host = "localhost";
$database = "kjnjkyeo3";
$user = "root";
$pass = "probajovo11";
//connection to the database
$connection = mysql_connect($host, $user, $pass, $database)
or die ('cannot connect to the database: ' . mysql_error());
$sql = "SELECT ps_orders.id_order, ps_order_detail.id_order, ps_order_detail.product_reference AS Itemno, ps_order_detail.product_quantity AS Saleqty, ROUND(ps_order_detail.total_price_tax_incl, 2) AS Cost, DATE_FORMAT(ps_orders.date_add , \'%Y%m%dT%T\' ) AS Dateoftrans\n"
. "FROM ps_orders\n"
. "LEFT JOIN kjnjkyeo3.ps_order_detail ON ps_orders.id_order = ps_order_detail.id_order";
//loop to show all the tables and fields
$loop = mysql_query($sql)
or die ('cannot select tables');
I made a lot of changes in my query but I always get the message cannot select tables. When I make a simple query like Select tables from $database, it works fine.
I made the changes:
//connection variables
$host = "localhost";
$database = "kjnjkyeo3";
$user = "root";
$pass = "probajovo11";
//connection to the database
$connection = mysql_connect($host, $user, $pass)
or die ('cannot connect to the database: ' . mysql_error());
//select the database
mysql_select_db($database)
or die ('cannot select database: ' . mysql_error());
$sql = "SELECT ps_orders.id_order, ps_order_detail.id_order, ps_order_detail.product_reference AS Itemno, ps_order_detail.product_quantity AS Saleqty, ROUND(ps_order_detail.total_price_tax_incl, 2) AS Cost, DATE_FORMAT(ps_orders.date_add , \'%Y%m%dT%T\' ) AS Dateoftrans FROM ps_orders LEFT JOIN ps_order_detail ON ps_orders.id_order = ps_order_detail.id_order";
//loop to show all the tables and fields
$loop = mysql_query($sql)
or die ('cannot select tables');
but it still doesn't work
$connection = mysql_connect($host, $user, $pass) or die ('cannot connect to the database: ' . mysql_error());
mysql_select_db($database);
$sql = "SELECT ps_orders.id_order, ps_order_detail.id_order,
ps_order_detail.product_reference AS Itemno, ps_order_detail.product_quantity AS Saleqty, ROUND(ps_order_detail.total_price_tax_incl, 2) AS Cost, DATE_FORMAT(ps_orders.date_add , \'%Y%m%dT%T\' ) AS Dateoftrans FROM ps_orders LEFT JOIN kjnjkyeo3.ps_order_detail ON ps_orders.id_order = ps_order_detail.id_order";
mysql_connect doesn't allow you to select the database like you are doing. You have to use mysql_select_db and one day you'll also have to eventually move to mysqli or PDO.
$connection = mysql_connect($host, $user, $pass) or die ('cannot connect to the database: ' . mysql_error());
mysql_select_db($database);
mysql_connect does not take a $database parameter. http://dk1.php.net/manual/en/function.mysql-connect.php, instead use:
$connection = mysql_connect($host, $user, $pass)
mysql_select_db($database, $connection)
Use mysql_select_db($database) to tell on which databases will the queries run.
If you are selecting from multiple databases you can use this way of referecing a field
`database_name`.`table_name`.`field_name`
or just
`database_name`.`table_name`
for a table in FROM.
mysql_* functions are deprecated, if you are starting a new project use mysqli or pdo

escaping mysql table not found

I have a script that continuously connects to a database and then truncates table in a loop fashion. The script breaks if there is not table found. How do i escape this to enable it run to the end?
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$username =$row['user_name'];
$url=$row['url'];
//$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
$db = mysql_select_db("ghcomm") ;
mysql_query ("TRUNCATE settings") or die("error settings". mysql_error());
}
Use IF EXISTS in your SQL.
Just replace the last statement :
mysql_query ("TRUNCATE settings") or die("error settings". mysql_error());
with :
mysql_query ("TRUNCATE settings IF EXISTS settings") or die("error settings". mysql_error());
That way you never trigger the die("error settings...") part.
Hope this helps !
Just change
or die("error settings". mysql_error());
to
break;
You have to use the new connection you create. Otherwise the connection from outside the loop will be used all the time:
$db = mysql_select_db("ghcomm", $conn);
mysql_query ("TRUNCATE settings IF EXISTS settings", $conn) or die("error settings". mysql_error($conn));

PHP DB Connection questions

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

Categories