check a SQL query with if / else in PHP - php

I'm a complete novice in this but try to learn a lot by myself / tutorials. However I can not seem to find the answer to this (probably) easy problem. I want to check an output from my SQL database if it is smaller than 10 and then give me the current value of the INT. If it is not yet 10 or more then I want to output a line and if so output an other line. However, it does not seem to work properly at the moment.
//Connect to DB
$con = mysqli_connect("localhost","root","root","cursuson");
//Get counter!
$getcounter = mysqli_query($con,"SELECT * FROM cursus01");
$cursus01 = mysqli_fetch_assoc($getcounter);
//check if output is less than 10
if(count($cursus01) <= 10)
echo 'aantal aanmeldingen is ' . $cursus01['counter'] . '<br>';
else
echo 'De cursus gaat door! <br>';
//check the output
echo '<b>Aantal aanmeldingen:</b> ' . $cursus01['counter'] . '<br>';
echo '<b>ID:</b> ' . $cursus01['id'];

I assumed that you were trying to get the count of rows from the database (as others have done) and have left the answer for if that were the case below this one. You might find it useful and it seems like a waste to delete it!
Anyway, judging from your comment above and the $cursus01['counter'] in your question I'm now going to assume that what you actually want is the following...
Solution
I suggest that you use the mysqli method below as mysql will at some point in the near future be removed from the language as it is deprecated! If you continue to use it and create sites/apps with it then when this eventually happens you'll either have to use an old version of php which has it's own risks/limitations attached or face having a lot of broken code to fix...
mysql
mysql_connect("localhost","root","root");
mysql_select_db("cursuson");
$query = mysql_query("SELECT * FROM cursus01");
if(mysql_num_rows($query)){
//Rows are returned
while($row = mysql_fetch_assoc($query)){
//Do stuff with row data
if($row['counter'] <= 10){
//Counter is less than or exactly 10
}
else{
//Counter is greater than 10
}
}
}
else{
//No rows were returned
}
mysqli
$mysqli = new mysqli('localhost', 'root', 'root', 'cursuson');
$result = $mysqli->query("SELECT * FROM cursus01");
if($result->num_rows;){
//Rows are returned
while($row = $result->fetch_assoc()){
//Do stuff with row data
if($row['counter'] <= 10){
//Counter is less than or exactly 10
}
else{
//Counter is greater than 10
}
}
}
else{
//No rows were returned
}
Original answer
I assume that you are actually trying to echo a count of the number of rows returned? Your current code echos a count of the number of coulmns. If you don't know already it would suggest that there are bigger problems here....
Solution
mysql
mysql_connect("localhost","root","root");
mysql_select_db("cursuson");
$query = mysql_query("SELECT * FROM cursus01");
$count = mysql_num_rows($query);
if($count <= 10){
//Less than (or exactly) 10 rows were returned
while($row = mysql_fetch_assoc($query)){
//Do stuff with row data
}
}
else if($count > 10){
//More than 10 rows were returned
while($row = mysql_fetch_assoc($query)){
//Do stuff with row data
}
}
else{
//No rows were returned
}
mysqli
$mysqli = new mysqli('localhost', 'root', 'root', 'cursuson');
$result = $mysqli->query("SELECT * FROM cursus01");
$count = $query->num_rows;
if($count <= 10){
//Less than (or exactly) 10 rows were returned
while($row = $result->fetch_assoc()){
//Do stuff with row data
}
}
else if($count > 10){
//More than 10 rows were returned
while($row = $result->fetch_assoc()){
//Do stuff with row data
}
}
else{
//No rows were returned
}

The way you're doing this, the count is going to be the same every time. You're count($cursus01) returns the number of columns in your database, to get the number of rows you should use the num_rows function or do a count query, unless you need the data from the query in which case you should do something like....
$cursus01 = array();
while($row = mysql_fetch_assoc($getcounter))
$cursus01[] = $row;
In this case count($cursus01) will return the number of rows. Hope i didn't confuse what you were asking. As edward pointed out you should start using mysqli instead of mysql. You also might want to look into using oop instead of procedural calls. see the manual for an example HERE

Agreed with Bryan answer, but when doing counts of database rows I'd choose the option of using MySQL count. In this case code line would be:
$getcounter = mysql_query("SELECT COUNT(*) FROM cursus01");
You will get the exact number of rows using this query

I assume you want to count the number of records stored in the table.
use mysqli_num_rows() function instead of count().
$con = mysqli_connect("localhost","root","root","cursuson");
$getcounter = mysqli_query($con,"SELECT * FROM cursus01");
$row = array();//create an empty array
//check if output is less than 10
if(mysqli_num_rows($getCounter) <= 10):
$row = mysqli_fetch_array($getCounter);
echo $row['counter']."<br>";
else:
echo 'De cursus gaat door! <br>';
endif;
//display the output
echo '<b>Aantal aanmeldingen:</b> ' . $row['counter'] . '<br>';
echo '<b>ID:</b> ' . $row['id'];

Related

Why is my MySQL search query returning column names and data?

I'm fairly new to PHP and I've been stumped on this issue for a while now (been searching everywhere but no help really).
I'm attempting to search for all the data in a data table ("Select * FROM X") and that seems to work fine.
However when I try to return/echo the data, encoding into JSON format as an array (I'd like 1 row as 1 index in the array) it does wierd things.
Heres the code I currently use;
$SQL = "SELECT * FROM `units`";
$Result = mysqli_query($link, $SQL) or die ("DB ERROR");
$Total = mysqli_num_rows($Result);
if($Total > 0)
{
$rows = mysqli_fetch_array($Result, MYSQLI_NUM);
$row_count = mysqli_num_rows($Result);
while($row = mysqli_fetch_array($Result))
{
echo json_encode(array($row));
}
}
This then gets used in Unity (C#) via;
JSONObject obj = new JSONObject(loadUnitsWWW.text);
Debug.Log(obj);
The results of which are;
[{"0":"2", "unitID":"2","1":"Tanks","unitName":"Tanks","2":"Ground","unitType":"Ground"},[],[],[],[],[],[],[],[],[],[],[]]
it seems to be trying to return EVERYTHING for some reason, including the column names. But I've no idea why it'd return the same results multiple times (and no idea where the 0 came from).
As I said, I'm fairly inexperienced with PHP, as such its very likely something (in fact I'm certain) something is wrong with that code, I've tried a for loop such as;
for($i = 0; $i < $row_count; $i++) {...}
but to no avail (it returns something like:
["1",[],[],"",null,null,null,{},null,null,null.null[],""..........]
Heres the data table layout if it helps;
unitID | unitName | unitType
1 | infantry | Ground <br>
2 | Tanks | Ground <br>
3 | Support | Ground <br>
4 | Artillery | Ground <br>
. <br>
.
There are 13 items in the table
EDIT:
THis is what I am expecting:
[["1", "Infantry","Ground"],["2","Tank","Ground"]....]
Here is how you should be doing this. comment in code
// Always use the field names. this is going to avoid debug nightmare later.
$SQL = "SELECT unitID, unitName, unitType FROM `units`";
$Result = mysqli_query($link, $SQL) or die ("DB ERROR");
$Total = mysqli_num_rows($Result);
if($Total > 0)
{
// initilize a new array
$data = array();
// Note use mysqli_fetch_row because you want only result values
while($row = mysqli_fetch_row($Result))
{
// add the row data to our array
$data[] = $row;
}
// encode the entire data and echo
echo json_encode($data);
}
Reference : mysqli_fetch_row
Edit: you can also do this like the following.
if($Total > 0)
{
// Get all the result at once and json_encode it!!
echo json_encode(mysqli_fetch_all($Result));
}
Reference: mysqli_fetch_all
Edit2: as per #YourCommonSense comment your code can be
$SQL = "SELECT unitID, unitName, unitType FROM `units`";
if ($Result = mysqli_query($link, $SQL))
{
echo json_encode(mysqli_fetch_all($Result));
} else die ("DB ERROR");
There are 2 issues with your php snippet:
if you look at the mysqli_fetch_array documentation, you'll notice that if you don't supply the second int $resulttype argument, it defaults to MYSQLI_BOTH; this means that both associative and numeric indices will be returned
you call mysqli_fetch_array on $Result twice, first assigning it to $rows variable, and second time inside the while condition assigning it to the $row variable
I'm guessing what you want to do is:
remove the $rows assignment
inside the while condition add the 2nd argument MYSQLI_NUM
0 refers to column order in the result set. You can refer to mysqli-result.fetch_array and check parameters and return type.
change your line:
while($row = mysqli_fetch_array($Result))
with:
while($row = $rows) {
// your code
$rows = mysqli_fetch_array($Result, MYSQLI_NUM);
}
Another solution, I think it is better for you
$rows = mysqli_fetch_all($Result, MYSQLI_NUM);
echo json_encode($rows);

How can I get this php to return the entire column of an sql db

I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}

How Can I Limit the Output from a PHP While Loop?

I have a while loop running that is returning values from a MYSQL table. It returns about 90 entries from the query. My hope is to be able to break these 90 values up and display them in groupings of 5. This may sound confusing so let me share some code samples to help clarify:
$con = mysql_connect("host", "username", "password") or die ("Unable to connect to server");
mysql_select_db("database") or die ("Unable to select database");
$sql = mysql_query("SELECT * FROM `table` WHERE column IS NOT NULL AND column <> ''");
Here I am pulling the values out that I need from the table...
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$column=$row['column'];
echo $id . '<br>';
echo $column . '<br>';
}
At this point, I have run the loop and get the display of all 90 entries. How can I pull the values out and display them in smaller chunks? If I use the looped values outside of the while loop, it just gives me the last value from the set. Is there a simple way to use the unique $id value from the column to get a specific grouping within the loop?
This will add more br's and a hr after each 5 records:
$cnt = 0;
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$column=$row['column'];
echo $id . '<br>';
echo $column . '<br>';
if($cnt % 5 == 0) echo "<br><br><hr><br><br>";
$cnt++;
}
Here is one (not very sophisticated) approach you could take:
$group_size = 5;
$tracking_variable = 0;
while ($row = function_to_fetch_row()) {
if ($tracking_variable == 0) {
// logic for the start of a grouping
}
// logic to display the row
$tracking_variable = ($tracking_variable + 1) % $group_size;
if ($tracking_variable == 0) {
// logic for the end of a grouping
}
}
if ($tracking_variable > 0) {
// logic for the end of the final grouping
}
You want to save this data in a variable, and reference it outside of the loop.
Try this:
$data = array();
while($row=mysql_fetch_array($sql))
{
$data[$row['id']] = $row['column'];
}
And now you can just display specific rows:
print $data[$someRow];

PHP getting data from mysql database for the Query string variable

Here is what I would like to do; I am passing an encoded data as a query variable to my webpage, then in my php page, I am decoding the data and checking the same in my database. The code I am using is shown below:
<?php
// Get the ID from URL.
$id = ( isset($_GET["id"]) && !empty($_GET["id"]) ? $_GET["id"] : "");
// If "id" is not empty, proceed.
if(!empty($id)) {
$id = base64_decode($id);
global $wpdb;
$res = $wpdb->query("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found.";
for( $i=0; $i<count($res); $i++) {
echo $res[$i]->id;
}
exit;
}
else {
echo "No ID";
exit;
}
?>
I have one record in my database. The above code correctly says "1 records found". I am not sure how to get the value of the field in that row. I have 3 columns, they are id, field1 and field2. The code "echo $res[$i]->id" returns nothing.
Please help
BTW, I am trying this in my Wordpress blog.
Thank you all for your suggestions. I tried your suggestions and here are my results:
$res = $wpdb->query("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";
it says 1 records found.
$res = $wpdb->get_row("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";
it says 0 records found.
$res = $wpdb->get_results("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";
it says 0 records found.
while ($row = mysql_fetch_array($res)) {
echo $row[0];
}
If I use mysql_fetch_array,
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/myfolder/mytheme/index.php on line 38.
line 38 is while ($row = mysql_fetch_array($res)) {.
What I am trying to accomplish:
I have a wordpress blog. All the above code goes into my index.php. I will pass a product id to my index.php via query string variable. I have created a new table called S_redirect in my wordpress database. I will retrieve the value of query string variable id and check the same in my database table. If record exists, then retrieve one of the column value (url of the product) from that table row and redirect to that product url. If the record doesn't exists then redirect to home page. hope this helps everyone to understand what I am doing.
Judging by $wpdb, it looks like this is a WordPress. Hopefully this will help:
http://codex.wordpress.org/Function_Reference/wpdb_Class
Update
Don't use count() to get the number of rows; use $wpdb->num_rows (no () because it's a property, not a function). The count() function always returns 1 for any non-null value that it doesn't recognize as a "countable" value (i.e., arrays and certain objects), so it's likely your code will always yield 1.
$tot = $wpdb->num_rows;
=====
If you run your query with get_results() instead of query(), then you can loop through the results like this:
foreach ($res as $row) {
echo $row->id;
}
Ultimately, I think your code will end up looking like this:
$res = $wpdb->get_results("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = $wpdb->num_rows;
echo $tot . " records found.";
foreach ($res as $row) {
echo $row->id;
}
Disclaimer: This is untested, as I've never used WordPress. This is just how I understand it from the documentation linked above. Hopefully it at least gets you on the right track.
Use:
$tot = count(mysql_fetch_array($res));
or
$tot = mysql_num_rows($res);
The best is
while($row = mysql_fetch_assoc($res)){
echo $row['column_name'];
}

How do I loop through MySQL results easily?

I've been requesting MySQL results and looping through them like this:
$query = "SELECT * FROM $table";
$result = mysql_query($query);
for($i = 0; $i < mysql_num_rows($result); $i++){
echo mysql_result($result, $i, $row);
//do something else;
}
you can probably see what happens. What if a row has been deleted? What if the first item is gone? In that case, there could be 30 items in the list, but the last items index is at position 50. How do I fix this or what other systems can I use?
while($temp = mysql_fetch_assoc($result))
{
echo $temp['id']; // ID Column
}
But BTW. The mysql_num_rows returns the number of rows you fetched. If you have a row that was deleted, it wouldn't have been fetched, and therefore it wouldn't count towards the number.
Also - I believe the entire rowset is obtained at query time, rows deleted after the query is executed will still appear in your results.

Categories