I am trying to view how many rows there are based on a SQL query using PHP.
I seem to be able query the database and return fields from a row but can't seem to find out how many rows there are based on the same query.
<?php
$host = 'localhost';
$user = 'MyUsername';
$pass = 'MyPassword';
$database = 'MyDatabase';
$con=mysqli_connect($host,$user,$pass ,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
mysqli_close($con);
?>
All it returns is the text Rows on the screen, without the number of rows at the start.
Like I said, this same query works and returns a value if I try and select a row using:
while($row = mysqli_fetch_array($result))
{
echo $row["test"];
}
Anyone know why it won't return the number of rows?
You are using MySQLi. Because of you don't have a mysql query, mysql_num_rows doesn't return desired value.
You have to replace your mysql function with mysqli equal:
$num_rows = mysqli_num_rows($result);
You are using Mysqli to you should use mysqli_num_rows
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysqli_num_rows($result);
If you want only count then you can directly use count(*) like this:-
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result;
I'll do some thing like this:
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result
Related
I am trying to count the total number of rows in a single table. Just need to know how many rows total and nothing else. I am using Oracle database.
I have tried
$sql = "SELECT COUNT(*) AS homes FROM homes";
But I am unsure on how to display the result.
$sql = "SELECT COUNT(*) AS count FROM homes";
To count the rows from
$sql = "SELECT * FROM homes"; // fetch the rows
$sql1=mysql_query($sql);
$count=mysql_num_rows($sql1) // count number of rows in table
echo $count; //$count has the value of rows in table..
Use this code:
// Code goes here
<?php
$sql = "SELECT COUNT(*) AS homes FROM homes";
$result = mysqli_query($sql);
$row = mysqli_fetch_array($result);
print($row['homes']); // prints count
?>
<?php
$link = mysqli_connect("host", "username", "password");
mysqli_select_db("database", $link);
$result = mysqli_query("SELECT * FROM homes", $link);
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
?>
I have a table in my database named visitor_table . Within table i have a column named visitor_affiliate. I want to get the count of the rows when visitor_affiliate = "someurer" .
I want to get the count as number. I already have this code but i don't know how to get the count only for the rows containing the string. I currently get the number of all rows,
$result = mysql_query("SELECT * FROM visitor_table");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
You can ask MySQL to return the count:
SELECT COUNT(*) FROM visitor_table WHERE visitor_affiliate = 'someurer'
You shouldn't be using the ancient (deprecated as of PHP v5.5.0, soon to be removed entirely) MySQL extension for writing new codeāuse instead the improved MySQLi extension or the PDO abstraction layer, both of which enable you to pass variables to the database in a safe, parameterised, fashion that ensures they are not evaluated for SQL (and therefore prevents SQL injection attacks):
$dbh = new PDO("mysql:dbname=$dbname", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$qry = $dbh->prepare('
SELECT COUNT(*) FROM visitor_table WHERE visitor_affiliate = ?
');
$qry->execute(['someurer']);
echo $qry->fetchColumn(), ' rows';
$result = mysql_query("SELECT * FROM visitor_table WHERE `visitor_affiliate` = 'someurer'");
$num_rows = mysql_num_rows($result);
echo $num_rows . " Rows\n";
With what little information you have given just try this-
$result = mysql_query("SELECT * FROM visitor_table Where visitor_affiliate like '%someurer%'");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
The deprecated MySQL:
$res = mysql_query('SELECT * FROM visitor_table');
echo 'Number of rows:'.mysql_num_rows($res);
Procedural MySQLi:
$tu = mysqli_prepare($DBH,'SELECT * FROM visitor_table');
mysqli_execute($tu);
$num_rows = mysqli_num_rows($tu);
echo $num_rows.' rows\n';
mysql has been deprecated. Please use mysqli.
Using MySQLi bind_param to get your result:
$someuser = 'Dave';
$DBH = mysqli_connect('localhost','user','pass','database');
$query = mysqli_prepare($DBH,'SELECT * FROM visitor_table WHERE user = ?');
mysqli_bind_param($query,'s',$someuser);
mysqli_execute($query);
mysqli_bind_result($id,$user,$tabCol1,$tabCol2);
while(mysqli_fetch_result){
$row = $row +1;
echo $user.': was found in the record with ID of: '.$id;
}
echo 'total records found:'.$row;
That's one way of doing it as I'm not completely 100% sure about using a mysqli_num_row() with the query above.
For ex. adress page test.php?prid=4477535
Code page test.php
function query($query) {
$database = 'test';
$host = 'test';
$username = 'test';
$password = 'test';
$link = mysql_connect($host,$username,$password);
if (!$link) {
die(mysql_error());
}
$db_selected = mysql_select_db($database);
if (!$db_selected) {
die(mysql_error());
}
$result = mysql_query($query);
mysql_close($link);
return $result;
}
$product_idn=$_GET['prid'];
$select_image = query("SELECT * FROM products_images WHERE `product_idn`='$product_idn'") or die(mysql_error());
foreach ($select_image as $row)
{
$select_image_array[]=$row->image;
}
print_r ($select_image_array);
receives a request
SELECT *
FROM products_images
WHERE `product_idn` = '4477535'
If make select from phpmyadmin i have 10 rows.
But if i use test.php?prid=4477535 i see empty page.
print_r ($select_image_array) not show array.
Tell me please why i see rows with phpmyadmin and not see rows with script?
Like the other said, you are prone to SQL injection since you don't serialize your input, but to fix your code, use this:
$select_image = query("SELECT * FROM products_images WHERE `product_idn`='$product_idn'") or die(mysql_error());
while($data = mysql_fetch_assoc($select_image))
{
echo $data['image'];
}
You are doing it wrong.
You have to fetch the resource (mysql_query returns a resource) into an array, and the keys of the array will be the names of the rows returned from your query.
$product_idn=$_GET['prid'];
$select_image = query("SELECT * FROM products_images WHERE `product_idn`='$product_idn'") or die(mysql_error());
while($fetch=mysql_fetch_assoc($select_image))
{
echo $fetch['image'];
}
print_r ($select_image_array);
BTW, You have a security hole here - SQL Injection.
Test the following
$result = query("SELECT * FROM products_images WHERE `product_idn`='$product_idn'")
$select_image = mysql_fetch_assoc($result);
var_dump($select_image);
for more information look at http://se2.php.net/mysql_query
You just
echo $row->image;
Never initialize $select_image_array
print_r ($select_image_array); won't show anything because there is no $select_image_array defined. Did you mean print_r ($select_image);?
Is query() a function you've defined? If not and you don't have errors on you are likely to see nothing.
You also need to sanitize your SQL. Simplest method for now since it's an integer:
$product_idn=(int)$_GET['prid'];
For example, for some queries like SELECT MAX(field), the query result is usually only a field value, rather than returning rows to you.
Now the field of the value I wanna get is integer type.
As I'm a beginner of php, how can I get that value from the query result?
As I do the following
$query = "SELECT MAX(stringid) FROM XMLString";
$result = mysql_query($query, $link);
echo $result;
Then nothing is echoed out.
I have check the db connection made by mysqlconnect, and it's got no problem.
And I tried this query in MySQL at phpMyAdmin, then the query is what I want, too?
So why would it be like that, and any solution?
Thanks!
You will always retrieve rows back from an SQL query, even if there's only one row with one field. You can directly retrieve a specific field of a specific row using mysql_result:
$query = "SELECT MAX(stringid) FROM XMLString";
$result = mysql_query($query, $link);
echo mysql_result($result, 0, 0);
$query = "SELECT MAX(stringid) as val FROM XMLString";
$result = mysql_query($query, $link);
$rows = mysql_num_rows($result);
if($rows > 0) {
$rstAry = mysql_fetch_array($result);
echo $rstAry['val'];
}
Try This
mysql_query is not printing results. Maybe try this:
echo mysql_result($result);
You are not getting any result because mysql_query returns a database object.
You will need to process this "database object" using mysql_fetch_array. This command 'fetches' an array out of a MySQL "database object". The array you are fetching is the rows your query produced. In your case, it is just one row.
Here is the code:
This step sets your query:
$query = "SELECT MAX(stringid) as val FROM XMLString";
This step will run your query, and return the database object:
$result_database_object_whatever = mysql_query($query, $link);
This step will process the database object, and give you an array of the queried rows:
$result_array = mysql_fetch_array($query, $link);
This step will echo the first row returned by your query:
echo $result_array[1];
You can do something like this:
$query = "SELECT MAX(stringid) FROM XMLString";
$result = mysql_query($query, $link);
$fetch = mysql_fetch_assoc($result);
echo $fetch['stringid'];
The mysql_fetch_assoc() function retrieves the data in an associative array.
Would it help to give the max a name you could reference? Also ifyou think there's syntax errors you could just add the error to help clarify.
$query = "SELECT MAX(stringid) as maxNum FROM XMLString";
$result = mysql_query($query, $link) or die(mysql_error());
echo $result;
How do I fetch only one value from a database using PHP?
I tried searching almost everywhere but don't seem to find solution for these
e.g., for what I am trying to do is
"SELECT name FROM TABLE
WHERE UNIQUE_ID=Some unique ID"
how about following php code:
$strSQL = "SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID";
$result = mysql_query($strSQL) or die('SQL Error :: '.mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['name'];
I hope it give ur desired name.
Steps:
1.) Prepare SQL Statement.
2.) Query db and store the resultset in a variable
3.) fetch the first row of resultset in next variable
4.) print the desire column
Here's the basic idea from start to finish:
<?php
$db = mysql_connect("mysql.mysite.com", "username", "password");
mysql_select_db("database", $db);
$result = mysql_query("SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID");
$data = mysql_fetch_row($result);
echo $data["name"];
?>
You can fetch one value from the table using this query :
"SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID limit 1"
Notice the use of limit 1 in the query. I hope it helps!!
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();