Variable 'data' might have not been defined - php

I'm working on a function that displays data but I keep getting warning "Variable 'data' might have not been defined"
function getAllData() {
$query = "SELECT * FROM patient, person WHERE patient.Patient = person.Personnummer ";
if(!$sql = mysql_query($query)) {
throw new exception("Error: CAn not execute the query.");
} else {
$num = mysql_num_rows($sql);
if($num>0)
{
for($i=0; $i<$num; $i++)
{
$data[$i] = mysql_fetch_array($sql);
}
}
}
return $data; //<--Variable 'data' might have not been defined
}

I guess it is your IDE that is giving you that warning, not php when you execute your script (it might, but the warning would be different).
To avoid it, make sure it is always defined:
function getAllData() {
$data = array();
$query = "SELECT * FROM patient, person WHERE patient.Patient = person.Personnummer ";
...
Now an empty array will be returned from your function if for example no rows are found. In your current code, php would generate a warning at run-time about an undefined variable when you run your script and no rows are found.

Related

Fatal Error uncaught error call to a member function fetch_assoc()on null in

Image for reference I just dont get where I am wrong. Can somebody help me with this? I feel stupid right now
function total_price() {
$total = 0;
global $con;
$ip = getIp();
$select_price = $con->query("SELECT * from shoppingcart WHERE IP_address='$ip'");
while($row = $select_price->fetch_assoc()) {
$pro_id = $row['Product_id'];
$quan = $row['Quantity'];
$query = $con->query("SELECT * FROM products WHERE prod_id='$pro_id'");
while($row2 = $query->fetch_assoc()) {
$row2['product_price'] *= $quan;
$productprice = array($row2['product_price']);
$values = array_sum($productprice);
$total += $values;
}
}
echo "₱: ".$total;
}
I think there your $con->query(...) fails and so you $select_price is FALSE and not an object with some member functions.
Check Out the documentation of $mysqli::query
http://php.net/manual/en/mysqli.query.php
If you want to get the sql error print the Result of $con->error.
For example:
$select_price = $con->query("SELECT * from shoppingcart WHERE IP_address='$ip'");
if($select_price == FALSE) {
echo "SQL-Error:".$con->error
exit;
}
while($row = $select_price->fetch_assoc()) {
...
if fetch_assoc fails there is a problem with your result set.
Problem ist that:
$query
or
$select_price
is not a valid Result-Set.
Reason could be that the Querys to the database fails.
you can check this by doing:
print_r($select_price);
print_r($query);
Should Output: Ressource ID #XX -> if not, check your Query direct agains SQL.
hope this helps

PHP variable can't be found

When using this PHP code
$random = 00000; //a random int
$gameCode = $random;
$players = 0; //An example number
echo "<h4>$players Players</h4>";
while(true) {
sleep(1);
$sql = "SELECT id FROM gamecode WHERE gamecode = '$gameCode'";
$result = $conn->query($sql);
if ($result->num_rows != $players) {
$players = $result->num_rows;
echo "<h4>$players Players</h4>";
flush();
}
}
I am 99% the variables cant be found as i get an error saying that it is not an object and it works when i define the variable in the while loop. (Which i cant do for reasons)
Notice: Trying to get property of non-object in /storage/ssd4/654/2919654/public_html/createcode.php on line (Lines trying to use $players and $gamecode)
Thanks
The only thing that should be an object in there is $result, I expect that the query has failed and $result == false
When you call $result->num_rows that will fail with the error message you are seeing.
Try adding this test in
$result = $conn->query($sql);
if (!$result) {
die('Something broke');
}

error php:1054 Notice: Undefined variable: data in C:\xampp\htdocs\awebarts\app\models\Display.php on line 39

I have an error Undefined variable return data.
<?php
function getData() {
$query = "SELECT * FROM `$this->tablename` ORDER BY `id` DESC";
if(!$sql = mysql_query($query))
{
echo mysql_errno();
}
else
{
$num = mysql_num_rows($sql);
if($num > 0)
{
for($i = 0; $i < $num; $i++)
{
$data[$i] = mysql_fetch_array($sql);
}
}
}
return $data;
}
?>
Define $data outside of the for loop.
function getData() {
$query = "SELECT * FROM `$this->tablename` ORDER BY `id` DESC";
$data = array();
if(!$sql = mysql_query($query))
...
PS: Stop using mysql_* functions. Switch to either MySQLi or PDO.
The problem is pretty clear. $data is not initialized properly under specific circumstances:
When the if statement "if(!$sql = mysql_query($query))" is true $data is never set
When the if statement "if($num > 0)" is false (aka $num <= 0) $data is never set.
Thus you get a notice that data is undefined as it only gets set if the first if is false and the second if is true.
To correct this and get rid of the message you need to initialize $data at the beginning of the function.

Nested While Loops php

I've been trying to get a series of nested loops working to select the database name from one table then query the selected table in that database, and add up the results and display the number of them and the database name.
I have gotten the code to work but it keeps displaying:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in
I have tried every way possible I have found online to help, but none work.
$resulta = mysql_query("SELECT dbname AF012 FROM Customer");
while($data = mysql_fetch_array($resulta))
{
$db = $data[' dbname '];
$result = null;
$result2 = mysql_query("SELECT changemade FROM $db.orders");
//looping through the results
while($row = mysql_fetch_array($result2))
{
//checking if any record is 1,2 or 3
if( ($row[‘changemade’]== 1) || ($row[‘changemade’]== 2) || ($row[‘changemade’]== 3) ) {
//if any match the if adding 1 to the counter
$counter ++;
}
}
unset($result2);
echo $db." ".$counter;
echo "<br>";
$counter = 0;
$result = null;
$result2 = null;
}
All the database connections are made and work fine, so it has nothing to do with that. Any help would be great.
You need to introduce error handling, also you can streamline your code. The current point of failure is querying the database and fetching from it, so you can encapsulate it into a function of it's own which will also reduce your code:
function mysql_query_array($query)
{
if (!$result = mysql_query($query)) {
throw new Exception(sprintf('Invalid query "%s", error: %s.', $query, mysql_error()));
}
return function () use ($result) {
return mysql_fetch_array($result);
};
}
With that little helper function, your code is now more compact and it has actual error handling:
$queryA = mysql_query_array("SELECT dbname AF012 FROM Customer");
while ($data = $queryA())
{
$counter = 0;
$queryB = mysql_query_array("SELECT changemade FROM {$data['dbname']}.orders");
while ($row = $queryB())
{
if (in_array($row['changemade'], range(1, 3))) {
$counter++;
}
}
printf("%s %s<br>\n", $db, $counter);
}
This is caused by the fact that mysql_query return false if the query fails, so one of your query fails and mysql_fetch_array() gets a boolean. Try changing $db = $data[' dbname ']; to $db = $data['dbname'];

mysql_num_fields(): supplied argument is not a valid MySQL result resource

I'm working on a custom CMS, made changes to the DB schema and presentation layer. I'm getting an error relative to mysql_num_fields and mysql_num_rows using the following section of code. Can someone give me an idea of why these errors are being raised?
public function viewTableData($db_name,$table_name,$fld01,$where_clause,$order_by,$asc_desc){
mysql_select_db($db_name);
if($fld01!="")
{
$sql = "Select $fld01 from $table_name";
}
else
{
$sql = "Select * from $table_name";
}
if($where_clause!="")
{
$sql=$sql." ".$where_clause;
}
if(($order_by!="")&&($asc_desc!=""))
{
$sql=$sql." ".$order_by." ".$asc_desc;
}
else if(($order_by!="")&&($asc_desc==""))
{
$sql=$sql." ".$order_by;
}
//return "<br/>sql :".$sql;
$result = mysql_query($sql);
$count_fields = mysql_num_fields($result);
$count_rows = mysql_num_rows($result);
if($count_rows>0)
{
$index = 0;
unset($this->data_array);
while ($row = mysql_fetch_assoc($result)) {
$this->data_array[] = $row;
} // while
//Finally we release the database resource and return the multi-dimensional array containing all the data.
mysql_free_result($result);
return $this->data_array;
}
}
Slap an echo mysql_error(); line after the mysql_query line to see the error from the server.
You don't test $result, which can be FALSE upon return from mysql_query()
Also, I would rewrite:
if($order_by!="")
{
$sql.=" ".$order_by." ".$asc_desc;
}
MySQL doesn't care about extra spaces here and there.

Categories