I want to get how many (possibly 0) times a particular number occurs in a particular column. I set the number in $contact_client_ID then do the SELECT query below.
$sql = "SELECT * FROM t_contacts WHERE contact_client_ID ='$contact_client_ID'";
$result=(mysqli_query($link, $sql));
$count_result= mysqli_num_rows($result);
echo "contact client ID $contact_client_ID xxxxx $count_result";
Instead of $count_result containing the number I want, it contains a result made up of the number I want and the contact_client_ID joined together and the result doesn't seem to be usable as a number in any following code.
So, if $contact_client_ID = 50 and there are 2 occurrences of it in the table, the output I get is:
contact client ID 50 xxxxx 250
I've looked at the manuals and examples all over the place (including here) and I can't see what I'm doing wrong.
There are multiple ways of doing this, more precisely you have the option, to either do the count in PHP, or make your SQL server do the counting and just return the number:
Do it in PHP:
What it requires is: - fetch all data; -make a counter variable; - loop trough the data, for each loop increase counter +1
For small tables you can use PHP, for bigger ones I advice doing it on the SQL, since for PHP to count it it must fetch all the data.
$counter=0;
$query = "SELECT * FROM t_contacts WHERE contact_client_ID ='$contact_client_ID";
$res = $con->query($query);
while ($row = $res->fetch_assoc()) {
$counter++;
}
Do it in SQL
Now the smarter way would be to do it on the SQL server ,as it would handle the load better;
I would say what /u/Adaleni wrote is pretty close to what I would use:
$sql = "SELECT count(contact_client_ID) as total FROM t_contacts WHERE contact_client_ID ='$contact_client_ID'";
$result=mysqli_query($link, $sql);
$count_result= mysqli_fetch_row(result);
echo "contact client ID $contact_client_ID xxxxx $count_result[0]['total']";
Lets just describe what he does:
we use COUNT() function in SQL, this makes the server count the number of occurances of contact_client_ID and then make (in the result) a new variable called "total"
we execute the query and get the result
We use mysqli_fetch_rowm this function gets the result row as an enumerated array
then we access that array (as we know its only 1 item, we accessed index 0) and we print the variable total which we made in step 1 - $count_result[0]['total']
Try this
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT * FROM t_contacts WHERE contact_client_ID ='$contact_client_ID")) {
printf("Select returned %d rows.\n", $result->num_rows);
Related
Working with WordPress, running a custom query to pull all records relating to a specific condition. When I run the query in phpmyadmin it returns all records, when I run the query through PHP code, only 2-5 results return, need to find out how to resolve this:
// get variables from form page
$txtReg = $_REQUEST['txtReg'];
$txtMsg = $_REQUEST['txtMsg'];
// connect to database
$mydb = new
wpdb('***','***','***','***');
// run the query to fetch all cell numbers from the region variable
$query = "SELECT * FROM tblusers WHERE `Region` ='$txtReg'";
$rows = $mydb->get_results($query);
// display all cell numbers from that region
foreach ($rows as $row) {
$txtCell = $row->Cell;
//doSendSMS($txtCell,$txtMsg);
echo $txtCell;
}
E.g there are 100 cell numbers in Region A, only a few are returned and echoed, not all 100 like it should be, so when I run the sms code (which is the actual function, echo is used just to test results), not all receive the sms.
#Caius Jard was correct about the settings in the database, it was in fact limited even though no limit clause was applied in the sql query itself. The code is functional in my setup but was limited by the default settings.
tested using:
$query = "SELECT * FROM tblusers WHERE Region ='$txtReg' LIMIT 100";
Just a little assistance, This is a pretty simple problem but it doesn't seem to work right. I am just comparing the value in a variable with all the values in a sql column. Same as if I were to compare a username input to the list of usernames in a sql column. This however is just to compare that the item id being stored in the column for that row is not an item id that is already in use.
I tested the value that I am getting back from the sql query and it is equal to the item id I typed in the input. What you will see below is the actual test to see if the id I am getting back is the one that I am looking for as well as the id of the row I can find that value in. The results I get is
2, 000002 (which is correct) that is what I am looking for.
$itemId = $_POST['itemId'];
if($sqlItemId = $dbCon->query("SELECT * FROM CVCinStoreCoins WHERE itemId = '$itemId'")){
while($data = $sqlItemId->fetch_assoc()){
printf("<p>%s, %s</p>", $data['id'], $data['itemId']);
die();
}
Then I took this out and tried to compare the value in the variable which is the same itemId already stored (000002). that is where I am going wrong.
I modified the code to look like this for further testing. Seems straight forward yet i am getting a FALSE response providing the latter echo statement "Item Id is not in use" But it is in the DB. I tried it a few different ways based on what I read in stackoverflow but none are giving me the right answer.
$sqlItemId = $dbCon->query("SELECT * FROM CVCinStoreCoins WHERE itemId = '$itemId'");
if($itemId == $sqlItemId){
echo "This item id is already in use. \n";
die();
} else {
echo "Item Id is not in use:";
die();
}
At one point I even tried a while statement to fetch the associated values prior to testing it but that didn't turn up a positive result either. Any suggestions?
Inside $sqlItemId you have the full table row (if any), not only its ID; change the SQL into a count and check the number of rows returned (if greater than 0 you have a duplicate):
$rowsCount = $dbCon->query("
SELECT COUNT(*)
FROM CVCinStoreCoins
WHERE itemId = '$itemId'
");
I don't know what $dbCon is (Doctrine DBAL? mysqli?) so I can't tell you how to use query's result.
Wy don't you just count it,
$result = $dbCon->query("SELECT COUNT(itemId) FROM CVCinStoreCoins WHERE itemId = $itemId");
if $result > 0
I am new to PDO, sorry that this is so simplistic.
Basically, I want to SELECT and both get the returned rows and the number of those rows, cheking for zero rows before processing further.
$rows = $conn->query('SELECT ...) allows me to foreach($rows as $row) but, as I said, I want to check for zero.
count($rows) always returns 1, even if there are no results(!).
I thought of using SELECT SQL_CALC_FOUND_ROWS followed by
$foundRows = $connection->exec('SELECT FOUND_ROWS() AS numRows'); but I am so dumb that I can't figure out how to get the number of rows from that.
Basically, I want to SELECT and both get the returned rows and the number of those rows,
you are selecting rows wrong way
$rows = $conn->query('SELECT ...')->fetchAll();
will actually give you $rows array which can be counted. However,
cheking for zero rows before processing further.
You don't need to count $rows for this. Just use $rows array itself:
id (!$rows) ... // no rows returned
As of the case where you INDEED need SELECT FOUND_ROWS() - then to get a result from the query, you should fetch it:
$foundRows = $connection->query('SELECT FOUND_ROWS()')->fetchColumn();
And remember that you should never use exec with PDO.
I'm wondering why my MySQL COUNT(*) query always results in ->num_rows to be equal 1.
$result = $db->query("SELECT COUNT( * ) FROM u11_users");
print $result->num_rows; // prints 1
Whereas fetching "real data" from the database works fine.
$result = $db->query("SELECT * FROM u11_users");
print $result->num_rows; // prints the correct number of elements in the table
What could be the reason for this?
Because Count(*) returns just one line with the number of rows.
Example:
Using Count(*) the result's something like the following.
array('COUNT(*)' => 20);
echo $result['COUNT(*)']; // 20
Reference
It should return one row*. To get the count you need to:
$result = $db->query("SELECT COUNT(*) AS C FROM u11_users");
$row = $result->fetch_assoc();
print $row["C"];
* since you are using an aggregate function and not using GROUP BY
that's why COUNT exists, it always returns one row with number of selected rows
http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html
Count() is an aggregate function which means it returns just one row that contains the actual answer. You'd see the same type of thing if you used a function like max(id); if the maximum value in a column was 142, then you wouldn't expect to see 142 records but rather a single record with the value 142. Likewise, if the number of rows is 400 and you ask for the count(*), you will not get 400 rows but rather a single row with the answer: 400.
So, to get the count, you'd run your first query, and just access the value in the first (and only) row.
By the way, you should go with this count(*) approach rather than querying for all the data and taking $result->num_rows; because querying for all rows will take far longer since you're pulling back a bunch of data you do not need.
I have a table A, with just two columns: 'id' and 'probably'. I need to go over a long list of ids, and determine for each one whether he is in A and has probability of '1'. What is the best way to do it?
I figured that it would be best to have 1 big query from A in the beginning of the script, and after that when I loop each id, I check the first query. but than i realized I don't know how to do that (efficiently). I mean, is there anyway to load all results from the first query to one array and than do in_array() check? I should mention that the first query should had few results, under 10 (while table A can be very large).
The other solution is doing a separate query in A for each id while I loop them. But this seems not very efficient...
Any ideas?
If you have the initial list of ids in array, you can use the php implode function like this:
$query = "select id
from A
where id in (".implode (',', $listOfIds).")
and probability = 1";
Now you pass the string as first parameter of mysql_query and receive the list of ids with probability = 1 that are within your initial list.
// $skip the amount of results you wish to skip over
// $limit the max amount of results you wish to return
function returnLimitedResultsFromTable($skip=0, $limit=10) {
// build the query
$query = "SELECT `id` FROM `A` WHERE `probability`=1 LIMIT $skip, $limit";
// store the result of the query
$result = mysql_query($query);
// if the query returned rows
if (mysql_num_rows($result) > 0) {
// while there are rows in $result
while ($row = mysql_fetch_assoc($result)) {
// populate results array with each row as an associative array
$results[] = $row;
}
return $results;
} else {
return false;
}
}
for each time you call this function you would need to increment skip by ten in order to retrieve the next ten results.
Then to use the values in the $results array (for example to print them):
foreach ($results as $key => $value) {
print "$key => $value <br/>";
}
Build a comma separated list with your ids and run a query like
SELECT id
FROM A
WHERE id IN (id1, id2, id3, ... idn)
AND probability = 1;
Your first solution proposal states that:
You will query the table A, probabyly using limit clause since A is a table with large data.
You will place the retrieved data in an array.
You will iterate through the array to look for the id's with probability of '1'.
You will repeat the first three steps several times until table A is iterated fully.
That is very inefficient!
Algorithm described above would require lots of database access and unneccessary memory (for the temporary array). Instead, just use a select statement with 'WHERE' clause and process with the data you want.
You need a query like the following I suppose:
SELECT id, probably FROM A WHERE A.probably = 1
If i understood you correctly, you should filter in the SQL query
SELECT * FROM A WHERE A.probably = 1