PHP Count SQL gives no result [duplicate] - php

This question already has answers here:
select count(*) from table of mysql in php
(12 answers)
Closed 7 years ago.
I want to Count a number of elements in a MySQL Table with the PHP element count, but when i try to give out the result it print 'Resource id #5' which is of course the id for succeeded MYSQL srcipts. If I type it in the SQL console it says I have got Syntax Error (#1064). Thats my code:
<?php
$dbhost = >>hostname<<;
$dbuser = >>user<<;
$dbpass = >>password<<;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db(>>database to be selected<<)
or die ("Database couldnĀ“t be found");
echo mysql_query('SELECT COUNT(*) FROM table'); ?>
Which mysql_fetch_ do i have to use?
Thanks for any effords and a happy new year
Tim

You have to fetch the result from the query.
$result = mysql_query('SELECT COUNT(*) AS count FROM table');
$row = mysql_fetch_assoc($result);
echo $row['count'];
You should also convert from the mysql extension to PDO or mysqli, but the basic structure is the same -- after performing a query you have to fetch the results as a separate step.

If you just looking for:
Which mysql_fetch_ do i have to use?
Than you can try these:
mysql_fetch_assoc();
mysql_fetch_array();
mysql_fetch_object();
Side note:
Also remember what Mr. Barmar said about the **PDO or mysqli_* **

Related

How to return integer of COUNT mysql query result in PHP [duplicate]

This question already has answers here:
How to get count of rows in MySQL table using PHP?
(3 answers)
Closed 2 years ago.
I'm just putting a simple PHP program together that simply counts the number of total rows in my database and returns the result as a JSON object when it recieves a get request from my frontend.
This should all be super simple but for the life of me I can't figure out how to retrieve the count result in a usable format. All I get from this is "null"
any ideas?
$con = mysqli_connect($servername, $username, $password, $dbname);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$query="SELECT COUNT(*) FROM database";
$result = mysqli_query($con,$query);
$count = mysqli_fetch_assoc($result);
echo json_encode($count);
You can use COUNT as to avoid a very long key.
Here's a code example
$sql = "SELECT COUNT(column) as count FROM mytable";
$stmt = mysqli_stmt_init($db);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$count = mysqli_fetch_assoc($result)['count'];
echo $count;
To display data in JSON you can try this:
echo json_encode(['count' => $count])
That by itself will not give you the count.
I would suggest that you start using MySQL object methods instead of functions.
You should also use the "as" satement as way to give a name to the column that has the count value; in my example that column will be known as C .
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT COUNT(*) as C FROM database";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
$row = $result->fetch_assoc();
echo $row["C"];
}
EDIT:
In the specific case of SELECT COUNT you'll only get 1 row, so for this specific example you could do just fetch_assoc().

Parse a url and return database rows [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
I'm trying to parse a url and connect to a database.
For instance when a user visits url.php?id=1 they should get a list of questions and answers related to that topic.
When I run the MySQL query
SELECT * FROM QuestionDB WHERE TopicID = 1
In phpmyadmin I get the desired rows.
Here is my code. I returns a blank document!
$topic = $_GET['id'];
$dbhost = 'host';
$dbuser = 'user';
$dbpass = 'pass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM QuestionDB WHERE TopicID = '$topic'';
mysql_select_db('mydb');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "Question :{$row['Question']} <br> ".
"Answer : {$row['Answer']} <br> ".
"Author : {$row['Author']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
I can't work out what I'm doing wrong. If I delete the WHERE TopicID = '$topic' portion of my query, this code does print out all the rows from my database.
Cheers in advance
You have a syntax error. The string concatenation with the variable fails.
You have to change this line :
$sql = 'SELECT * FROM QuestionDB WHERE TopicID = "'.$topic.'"';
or
$sql = "SELECT * FROM QuestionDB WHERE TopicID = '$topic'" ;
Important note : Your code is vulnerable to SQL injections and may compromise the security of your database. You should use PDO or mysqli APIs to secure your SQL queries, and using prepare function.

PHP get data from DB not working [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
Can you figure out my code? All the code does is: No database selected It won't get the data from the db. The server os is Ubuntu or OS X. I been pulling my hair out for hours.
<?php
mysqli_connect("localhost", "root", "");
mysql_select_db("hit-counter");
$sql_get_count = mysql_query("SELECT id FROM hit_info ORDER BY id DESC LIMIT 1");
if($sql_get_count === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_assoc($sql_get_count)) {
print_r($row);
}
?>
I try this, it does the same
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("hit-counter");
$sql_get_count = mysql_query("SELECT id FROM hit_info ORDER BY id DESC LIMIT 1");
if($sql_get_count === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_assoc($sql_get_count)) {
print_r($row);
}
?>
you have an error in your code. You use mysqli_ function to connect the server but you use a deprecated function mysql_ to select the database.
Try this code:
mysqli_connect("localhost", "root", "");
mysqli_select_db("hit-counter");
Another option when using mysqli_ is to select the database you want during connecting to the server:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
You didn't mention database name:try this
<?php
$con = mysqli_connect("127.0.0.1","root","654321","testV2") or die("Some error occurred during connection " . mysqli_error($con));
// Write query
$strSQL = "SELECT id FROM did ORDER BY id DESC LIMIT 1";
// Execute the query.
$query = mysqli_query($con, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo $result["id"]."
";
}
// Close the connection
mysqli_close($con);
?>
You cannot interchange the mysql and mysqli functions, please modify your mysql_select_db to mysqli_select_db.
I will not go over the errors everyone else has pointed out. But, I will mention one that no one has. I think the - character in your database name will also cause problems. You should enclose the database name in back ticks. The back tick is this ` character, most likely the far left key above the TAB key. If you had error reporting turned on, or looked at your php error log, you would have seen the error.

how to fetch a random item/text quote from a column of a table using php/mysql [duplicate]

This question already has answers here:
Selecting random rows with MySQL
(3 answers)
Closed 8 years ago.
bellow you can see my table. In this table we have 300 quotes that I'm trying to fetch my at random and display it on the page but I have not succeeded. The column containing the texts has the name "fortune_text". here is my attempt code:
<?php
$username = "fortunes";
$password = "xxxx";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
// connect to database
mysql_select_db("fortunes");
// query the databse
$query = mysql_query("SELECT 'fortune_text' FROM 'fortunes' ORDER BY RAND()");
echo "$query";
?>
try using shuffle() function of php to randomize array that comes from database and then echo the first index of that variable.
Hi here is the modified version of your sample, which fetch text by rand order.
I suggest you to use limit when you print result to page if you have later many rows, checking for error if any. Important line is echo mysql_result($result);
<?php
$username = "fortunes";
$password = "xxxx";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
// connect to database
mysql_select_db("fortunes");
// query the databse
$result = mysql_query("SELECT 'fortune_text' FROM 'fortunes' ORDER BY RAND()");
if (!$result) {
die('Could not query:' . mysql_error());
}
echo mysql_result($result);
mysql_close($dbhandle);
?>

mysql php : switching between mysql databases is slow

In my php script which connects to mysql, I have to query 2 databases in the same script to get different information. More specifically Faxarchives in one database and Faxusers in the other.
In my code I query faxusers and then foreach user, I query Faxarchives to get the user history.
I might do something like:
function getUserarchive( $userid) {
$out= "";
$dbname = 'Faxarchive';
$db = mysql_select_db($dbname);
$sql = "select sent, received from faxarchivetable where userid = '" . $userid . "'";
if ( $rs = mysql_query($sql) {
while ($row = mysql_fetch_array($rs) ) {
$out = $row['sent'] . " " . $row['received'];
}//end while
}//end if query
return ($out);
}//end function
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'Faxusers';
$db = mysql_select_db($dbname);
$sql="select distinct userid from faxuserstable";
if ( $rs = mysql_query($sql) {
while ($row = mysql_fetch_array($rs) ) {
$out = $row['userid'] . ":" . getuserarchive($row['userid']);
}//end while
}//end if query
I'm guessing the switching between databases for each user is causing the slowness. Anyways how i can improve the speed of the processing?
thanks in advance.
You have several problems. First, your function, getUserarchive, pulls back all rows all the time. Looks like you forgot to restrict your SQL to only a specific userid. That's a big cause of your speed issues.
Another option would be to pass in all userids you are interested in. Rewrite the SQL as SELECT sent, received FROM faxarchivetable WHERE userid IN (...), which means you'd have one select to pull back all info from your faxarchivetable, instead of one per each userid.
Finally, if both databases are on the same MySQL server, you could just do a single select to pull in all the information:
SELECT Faxusers.faxuserstable.userid, sent, received FROM Faxusers.faxuserstable JOIN Faxarchive.faxarchivetable ON Faxusers.faxuserstable.userid = Faxarchive.faxarchivetable.userid
Are you aware that you can query tables in separate databases by qualifying the tablename?
For example, I think you can get all your information in a single SQL query like this:
SELECT sent, received
FROM Faxarchive.faxarchivetable
WHERE userid IN ( SELECT DISTINCT userid FROM Faxusers.faxuserstable );
Oh, this is the same point ChrisInEdmonton makes. I didn't notice his answer.

Categories