This works well, except that the last row always returns false. I've use this multiple times within my site and no matter what query I run, the last row always returns false instead of the data in the last row.
So if I have a query that should return 2 rows, it returns 1 row and false. I'm not really sure why.
function query2array($query, $sql_con) {
$result = mysql_query($query,$sql_con);
if(!$result) {
return false;
}
else if (mysql_num_rows($result) > 0) {
//set entire result to array
while($arr_data[] = mysql_fetch_array($result));
var_dump($arr_data);
if(count($arr_data) > 0) {
return $arr_data;
}
}
return false;
}
I'm new to PHP and I've read the documentation on mysql_fetch_array and just can't seem to figure out what's going wrong here. (I also know that I should be using mysqli, but I picked up on a site developed by someone else)
Try this:
while($row = mysql_fetch_array($result))$arr_data[] = $row;
The reason of such behaviour is you appending mysql_fetch_array() result to array without checking if it successfully retrieved.
As of manual:
Returns an array of strings that corresponds to the fetched row, or
FALSE if there are no more rows.
NOTICE: MySQL (mysql*_ functions) extension is deprecated. I suggest to use MySQLi (mysqli*_ functions) or PDO instead.
Related
I am confused as to why my code returns true when I expect false and the other way around. Here's my code:
public function CheckMac($mac){
$database = new Database();
$db = $database->connectDatabase();
$checkedmac = $db->prepare("SELECT * FROM `displays` WHERE `displayMac` = '$mac'");
$checkedmac->execute();
$count = (int)$checkedmac->fetchColumn();
if ($count > 0) {
return true;
} else {
return false;
}
}
I have the query right, when I echo $macand put it inside the query, phpMyAdmin gives me back the expected line, since it exists in the database, but when I run this code, I'm getting a false return.
Where did I go wrong on this one?
There is a fantastic yet underestimated answer, If your code is doing something unexpected, there's a good chance you're making an assumption somewhere.
You are yet to learn the cornerstone concept in the art of programming called debugging. Which means you are supposed to verify every single assumption you made.
You are assuming here that when a query returns a row, the (int)$checkedmac->fetchColumn(); statement returns a positive number. So you have to verify it.
I can make an assumption that the first column in your table does not contain a positive number but rather a string. A string cast a number will return 0. It will explain why you're getting 0 when a record is found. But you have to verify it as well.
If my assumption proves to be true, simply select a constant value instead of rather uncertain *. You can use 1 for example, and your query will work flawlessly:
public function CheckMac($db, $mac){
$stmt = $db->prepare("SELECT 1 FROM `displays` WHERE `displayMac` = ?");
$stmt->execute([$mac]);
return $stmt->fetchColumn();
}
A couple notes:
you should always connect only once. Create a $db variable beforehand in a single place and then use it everywhere
you are using a cargo cult prepared statement that protects from nothing. It should be always the way shown in my example.
if ($count > 0) return true is a tautology. A $count > 0 statement already returns true or false, so you can return its result rigtht away, without a superfluous condition
moreover, 1 is as good as true in PHP. So in the end you can return the result of fetchColumn() right away. in case the row is found it will be 1 equal to true and just false otherwise.
I am doing a select in my Oracle database and need to take different actions for the result being false (contains no results) or being true (contains one or more results).
However testing the result in the following way gives me a problem. In the cases where I actually have results from my query the if(! naturally validates to false and moves on to the else statement - perfect!
But when doing this test the internal pointer moves in the result and thereby the first result is lost when performing the while statement later.
if (!($row = oci_fetch_array($get_doc_paths, OCI_ASSOC+OCI_RETURN_NULLS))){
do something
}
else {
while ($row = oci_fetch_array($get_doc_paths, OCI_ASSOC+OCI_RETURN_NULLS)){
do something with $row
}
}
How do I test if there are results without moving the internal pointer?
In MySQL I would have used the mysqli_num_rows or simply just reset the pointer. I can't find a way to do this with Oracle.
$status = false;
while($row = oci_fetch_array(...)) {
$status = true;
// Do something with row
}
if(!$status) {
// Do something else
}
IF I use the !empty() on an sql query it doesn't say it is empty even if no rows are returned. e.g.
$result = $conn->query($sql_ideas);
if ( !empty($result)) {
while($row = $result->fetch_assoc()) {
$highlights[] = array($row["summary"], $row["detail"]);
}
-- Do stuff --
}
It just carries on as though a result is returned. Am I doing something wrong or is there a way to fix this?
Assuming you're using mysqli, your result object will actually be a 'mysqli result' - a class in it's own right. Checking that the row count is greater than zero is going to be the way to go.
http://php.net/manual/en/mysqli-result.num-rows.php
So, here's my issue: I have a function that queries sql and pulls it into a resource. In this function, I run:
if (odbc_num_rows($rs) === 0) {
return FALSE;
} else {
if ($type !== "Issues") {
while (odbc_fetch_row($rs)) {
$issues['tvi'][] = odbc_result($rs, 'TitleVolumeIssue_c_');
}
}
return $rs;
}
This does exactly what it is supposed to do. However, when I pass $rs into the next method for parsing into html, it seems as though $rs gets unset. Oddly, I can call odbc_num_rows($rs) and it gives me the correct number of rows, but dumping the var shows it is false and I can't loop through the resource to get any values.
How can I either free up that resource so that it can be used in the next function or how can I rewrite the IF condition so that I get the values without unsetting the resource?
Each time you fetch it moves the database cursor to the next row.
So odbc_fetch_row() keeps going to the next row, until the last one. After that it returns false.
Unfortunately you cannot move the row pointer back to the first record.
You will have to query your DB one more time.
Another option for this would be to store the odbc result in an array that you can loop through using a foreach. This preserves the data and you only have to query once vs multiple times (helps when dealing with a lot of data).
while($row = odbc_fetch_array($rs)) {
$resultsArray[] = $row;
}
Then loop through it like this...
foreach ($resultsArray as $key=>$value){
//Do what you need to do...
}
I had a similar problem in my question here and #Jeff Puckett was able to explain it pretty well.
What I mean is, for example, if I search for something on an SQL table, and it returns 0 / nothing, is that null or empty or does it result in an empty ""?
I'm getting back into php and trying to loop through a db like so:
Pseudo code:
while($row = mysqli_fetch_array($var here that has the query to the db and connection)){
echo $row[//something pulled from table to be read back]
}
But let's say that the search query didn't return any results or that $row doesn't equal to anything because for whatever reason, the value searched for in the db doesn't exist,
How then can I check for the empty-ness of row?
if the searched for item doesn't exist in the db, then $rows value becomes what exactly? null/empty/or empty string or something else?
depending on the value of row, do I test for [isset / !isset] or [empty / !empty] ? Or is the only way to test for empty $row to do a (pseudo) $x =mysqli_num_rows(var here) / if ($x == 0 ) //do something?
If mysqli_fetch_array did not return anything, then the return value is NULL
The line while($row = mysqli_fetch_array is supposed to return the next available record in the record set, so if the query did not give any matching results, then the line echo $row['something'] does not get executed at all.
If there are multiple fields you are fetching, say field1, field2 and supposing field2 doesn't have a value, then what is returned for that field is what the default value for that field will be in MySQL (or whichever DB you are using). However the point to note is that $row will still have two keys defined correctly as $row['field1'] and $row['field2']
If you want to check if $row['field2'] does have any value you can check it using empty($row['field2']).
"", 0, NULL, FALSE, array() are all considered empty() so you should be able to safely determine if the field has any valid value in it using this function. However, if say 0 could be a valid value (for e.g. you are querying no_of_days a person was absent last month and some of them have full attendance), you will need to explicitly check the value in the field and cannot depend on empty().
You can check whether there is result using mysql_num_rows. If there is items exist in that row, the row should have show one or more or TRUE depending on the item you searched, if nothing exist in database when you executed the query means the mysql_now_rows will show you 0/NULL.
You can do like
$query = mysql_query("YOUR QUERY HERE");
$numrow = mysql_num_rows($query);
if ($numrow == 0)
{
ECHO "No result found.";
}
When there's nothing, $row == false
That's the correct test on the while loop!
You can use mysqli_num_rows to fetch the number of results found by a query.
$query = 'SELECT `blah`';
$result = mysqli_query($query);
if(mysqli_num_rows($result) > 0) {
// do stuff here if any rows are found
} else {
// do stuff here if NO rows are found
}