I need to count the number of instances of a word in a column from my database and then get a true or false result depending on if it exceeds 36 instances. I use wordpress and I know that the connecction to the database is correct. And I am using wordpress.
This is what I got this far but its not working:
$selected = mysql_select_db("bringes_phpbb3", $dbConn) or die("Could not select database. The error was ".mysql_error());
mysql_query("SET NAMES utf8");
$SQL_COUNT ="SELECT COUNT(field_name) AS total_number FROM cyklister WHERE grupp LIKE CONCAT ('%','word','%')";
$result = mysql_query($SQL_COUNT);
if ($result >= 36){
$awnser = true;
mysql_free_result($result);
mysql_close($dbConn);
The SQL query is not complete or may be far from what I am looking for. Can someone help me?
After executing mysql_query, you need to call mysql_fetch_array to retrieve the result:
$result = mysql_query($SQL_COUNT);
$row = mysql_fetch_array($result);
$count = $row[0];
if ($count >= 36) {
$awnser = true;
}
Related
This question already has answers here:
How to get count of rows in MySQL table using PHP?
(3 answers)
Closed 2 years ago.
How do I display this query result:
from MySQL onto a webpage, just like this:
?
I want to display the count only. I did run the same query through PHP but its returning '2'. The PHP code is below
<?php
//Connection for database
$conn = mysqli_connect("localhost", "root", "aaaaa", "db");
$query = "SELECT `gender`,COUNT(`gender`) FROM `reg` GROUP BY `gender`";
$result = mysqli_query($conn, $query);
if ($result)
{
// it return number of rows in the table.
$row = mysqli_num_rows($result);
if ($row)
{
printf("" . $row);
}
// close the result.
mysqli_free_result($result);
}
// Connection close
mysqli_close($conn);
?>
Please note that I have gone through other answers like this one but I can't really find my way through, I want the value count only not the total number of all rows in the table, .e.g. count for 'Male'.
You're using mysqli_num_rows(), which returns the number of rows in the result, not the actual data in the result. For that you need to use mysqli_fetch_assoc().
Your could would become:
$query = "SELECT `gender`,
COUNT(`gender`) AS `count`
FROM `reg`
GROUP BY `gender`";
$result = mysqli_query($conn, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$gender = $row['gender'];
$count = $row['count'];
echo "$gender = $count<br>";
}
mysqli_free_result($result);
}
Note that I slightly changed your query to make the count accessible.
I have tables in one db, and one is foreign keyed to the other. My problem is that I'm trying to call up information stored in one table based on the user name which links the 2 tables stored in the other. Here is my php, mind you I'm pretty fresh on the databasing and php, so cut some slack. Here is my code:
<?php
$loaduser= $_SESSION['username'];
$loaduser_conn= #mysql_connect("DB_NAME","DB_USER","DB_PASS");
mysql_select_db("user_register") or die ("Couldn't find user database.");
$gal_result= mysql_query("SELECT shoot_name FROM images WHERE username='$loaduser'") or die (mysql_error());
while($row = mysql_fetch_assoc($gal_result,MYSQL_ASSOC))
{
foreach($results['shoot_name'] as $result)
{
echo $result['shoot_name'], '<br>';
if(mysql_num_rows($gal_result) !=1) {
die("No galleries found for this user.");
}
}
}
You can google "PHP PDO tutorial" and find many resources. Here's one that is very clear and well written: like: https://phpdelusions.net/pdo
Here's a better example:
<?php
$loaduser = $_SESSION['username'];
// use PDO, not the deprecated mysql extension
$dsn = "mysql:host=localhost;dbname=user_register";
$conn = new PDO($dsn, "DB_USER", "DB_PASS");
// set exception errmode, so code dies automatically if there's an error
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// use a parameterized query instead of concatenating variables into SQL
$sql = "SELECT shoot_name FROM images WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$loaduser]);
// fetch all into an array of results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// check the count of the results with < 1 instead of != 1
// in case it's 2 or more
if ($stmt->rowCount() < 1) {
die("No galleries found for this user.");
}
// loop through results
foreach($results as $row) {
// use dot for string concatenation instead of comma.
echo $row["shoot_name"] . "<br>";
}
$results has to be fetched before tryin to get its contents.
While trying to get its contents you were fetching $row instead of $results
You are using mysql, mysql has been deprecated try using mysqli or PDO in the future.
Try this anyway.
<?php
$loaduser= $_SESSION['username'];
$loaduser_conn= #mysql_connect("DB_NAME","DB_USER","DB_PASS");
mysql_select_db("user_register") or die ("Couldn't find user database.");
$gal_result= mysql_query("SELECT shoot_name FROM images WHERE username='$loaduser'") or die (mysql_error());
$results = mysql_fetch_assoc($gal_result,MYSQL_ASSOC)
while($results = mysql_fetch_assoc($gal_result,MYSQL_ASSOC)){
foreach($results['shoot_name'] as $result) {
echo $result['shoot_name'], '<br>';
if(mysql_num_rows($gal_result) !=1){
die("No galleries found for this user.");
}
}
}
?>
Try rewriting to this untested snippet (in case you want to keep using deprecated code ;))
$loaduser= $_SESSION['username'];
$loaduser_conn= #mysql_connect("DB_NAME","DB_USER","DB_PASS");
mysql_select_db("user_register") or die ("Couldn't find user database.");
$gal_result= mysql_query("SELECT shoot_name FROM images WHERE username='$loaduser'") or die (mysql_error());
if(mysql_num_rows($gal_result)==0){ // returns number of rows so if 0 there are no rows
die("No galleries found for this user.");
}
while ($row = mysql_fetch_array($gal_result)) { // "while" is already your loop. No need for the foreach within.
echo $row['shoot_name'], '<br>';
}
If you want to select from multiple tables with some reference try this query:
$gal_result= mysql_query("SELECT shoot_name FROM images AS a LEFT JOIN your_other_table AS b ON a.username = b.username WHERE a.username='$loaduser'") or die (mysql_error());
Like anyone i would advise you on using more up to date code.
See here for more info: http://php.net/manual/de/function.mysql-query.php
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
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;
I've been struggling with this problem for a couple of days and can't make any progress...
I'm trying to get just ONE result from my database but on contrary I'm getting the whole table : (
php:
{
$connect = #mysqli_connect ($host, $username, $pass, $dbname)
OR die ('Could not connect to MySQL');
$table = $_REQUEST['table'];
$key = $_REQUEST['id'];
$key_value = $_REQUEST['id_value'];
$q = "SELECT * FROM ".$table." where ".$key."='".$key_value."'";
$r = #mysqli_query ($connect, $q);
while ($row = mysqli_fetch_array($r))
$output[]=$row;
print(json_encode($output));
}
I think there's no need to show you my android code for that since the data is received well (also updating tables works fine) ... all i want is to get that ONE result from my DB.
When simply navigating to this file on the browser there's no problem obviously...
Thanks in advance, cheers
You are doing something like where 1 = 1 and that is always true. You are not naming your column. You are replacing that with a number.
try this (unverified):
"SELECT * FROM ".$table." where id='".$id."'";
If you want to get just the first row of the results, then you have two options:
include LIMIT in your query (preferred solution)
SELECT * FROM ".$table." where ".$id."='".$id."' LIMIT 1"
don't loop to get all the data, simply read the first row and return it.
$table = $_REQUEST['table'];
$key = $_REQUEST['id'];
$key_value = $_REQUEST['id_value'];
$q = "SELECT * FROM ".$table." where ".$id."='".$id."'";
You're assigning $key and $key_value but then using $id.
you are setting your condition to where ".$id."='".$id."'";, so, if you pass id=1, that will mean: WHERE 1=1, and that is always true. that's why it's returning all the records.