PHP print_r num_rows => 9 but blank page - php

Previously I use the PHP file from my own hosting, but the problem occurred when I moved to my client's (GoDaddy).
I have two inputs - Automotive and Education (I have more but for this question, I just use two as example)
In my own, both input will print the output without problem. But in GoDaddy, only Education can produce output, while Automotive produce blank page. So I add this code:
echo '<pre>';
print_r($res);
echo '</pre>';
For input Automotive, I got:
<pre>mysqli_result Object
(
[current_field] => 0
[field_count] => 1
[lengths] =>
[num_rows] => 9
[type] => 0
)
</pre>
For input Edication, I got:
<pre>mysqli_result Object
(
[current_field] => 0
[field_count] => 1
[lengths] =>
[num_rows] => 4
[type] => 0
)
</pre>
[{"subcategory":"Adult & Continuing Education"},{"subcategory":"Early Childhood Education"},{"subcategory":"Educational Resources"},{"subcategory":"Other Educational"}]
What I have done so far:
Check the query - No problem. The query return the desired result in phpmyadmin
Increase memory limit - Done but in PHP setting, still stated as Default even after refresh the Dedicated IIS Application Pool
I have other input with its output/num rows more than 9 but it return the result without problem
PHP code:
<?php
if($_SERVER['REQUEST_METHOD']=='GET') {
require_once('dbConnect.php');
$category = $_GET['category'];
$sql = "SELECT subcategory FROM wg_categories WHERE category = '$category'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('subcategory'=>$row[0]
));
}
echo json_encode($result);
mysqli_close($con);
}
?>
Is there something I have missed?
error_reporting - E_ALL
display_errors - on
log_errors - on

After reviewing php.net, the problem maybe at $row[0]. because the first element returned maybe $row[1]; to match the row id's in MySQL. So that maybe where the break is happening because it's accessing an element that may not exist.
http://php.net/manual/en/function.array.php
It may also be an issue with how MySQL is returning the array. Look at the below link for help, MySQLi driver maybe returning the array, as an Array of arrays or as an associative array, which is where the issue is coming from.
http://php.net/manual/en/mysqli-result.fetch-assoc.php
You may need to do the rows as associative. So using the actual column names. Like id, firstname, lastname etc. IE, $row['id']; $row['table_name'];
You may also want to try adding a try catch block, and then var dumping to see what is actually being returned or what everything looks like at that particular time. Then removing it once you have figured out what is going wrong.
http://php.net/manual/en/language.exceptions.php

Related

PHP not echoing variables when print_r does

I'm not sure exactly what is going on but when a user clicks a submit button on an html page and the php script runs I get the print out from the print_r statement, but if I print a variable out with the echo statement, the value isn't returned. I've just ported the webpage and code over to a new computer, would that have something to do with it? Here is my sample php code:
<?php
print_r($_POST);
$x = $_POST[minAcres];
echo $x;
?>
Everything was working fine until I moved the code. Any thoughts why this would be happening? Here is a screenshot of the output from the print_r command.
Here is an example I regress back to the original answer of needing just quotes around minAcres. As a proof of concept i filled in post array with the beginning few values from your screen shot. minAcres = 0. Output = '0'. Maybe your output has been formatted to not show the 0 but show blank/empty
<?php
$_POST = array(
'selectCountries' => array('Columbia'),
'startDate' => '2001-01-01',
'minAcres' => 0
);
print_r($_POST);
$x = $_POST['minAcres'];
echo $x;
?>
Output:
Array
(
[selectCountries] => Array
(
[0] => Columbia
)
[startDate] => 2001-01-01
[minAcres] => 0
)
0
Simple syntax error
$x = $_POST['minAcres'];
quotes needed around array's key.

PHP: `strcmp` serialization of identical object and array failing

I have a legacy app where i am trying to migrate changes from the old into the new while generating a log of changes. Things are going well; however, I keep running into "changes" that change nothing. After digging into this, I found that the legacy code is using arrays and the new code is using objects. If serialized, I thought they would be identical. After all, if they are dumped via print_r they are identical. But that is not the case. Even more astounding, the objects keep their integer keys even after serialize-unserialize cycling them.
The request is: how can I show these two strings are identical since their resulting object/array is identical save for key typing.
<?php
$v3v = 'a:2:{s:9:"lastindex";s:1:"1";i:1;s:1:"1";}';
$v4v = 'a:2:{s:9:"lastindex";i:1;i:1;s:1:"1";}';
$v3 = unserialize($v3v);
$v4 = unserialize($v4v);
die('<pre>'.print_r($v3,true).' '.print_r($v4,true));
outputs (the identical):
Array
(
[lastindex] => 1
[1] => 1
)
Array
(
[lastindex] => 1
[1] => 1
)
so let's now bring them "back to life":
$v3v = serialize($v3);
$v4v = serialize($v4);
die('<pre>'.print_r($v3v,true).PHP_EOL.print_r($v4v,true));
whaaa? how did you remember your integer keys??"
a:2:{s:9:"lastindex";s:1:"1";i:1;s:1:"1";}
a:2:{s:9:"lastindex";i:1;i:1;s:1:"1";}
and how can i get you to stop???
You can use array_diff instead of strcmp. You can try this -
$v3v = 'a:2:{s:9:"lastindex";s:1:"1";i:1;s:1:"1";}';
$v4v = 'a:2:{s:9:"lastindex";i:1;i:1;s:1:"1";}';
$v3 = unserialize($v3v);
$v4 = unserialize($v4v);
echo empty(array_diff($v3, $v4)) ? 'Identical' : 'Not Identical';
array_diff($v3, $v4) will return empty array if they are indentical.
Working code

Can't access fetched data from PDO query [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to create a dropdown-list with options (genres) from my database. For example if I have comedy, thriller and action in my database, these genres will be available as options on my dropdown-list. Basically what happens is that I get a blank list with no options and I was wondering if there is any problem with my code. Thanks in advance.
<?php
$sql = 'SELECT DISTINCT Genre.name FROM (Genre JOIN Movie2Genre ON Genre.id = Movie2Genre.idGenre)';
$stmt = $db3->prepare($sql);
$stmt->execute();
$allGenre = $stmt->fetchAll();
echo "<select>";
foreach ($allGenre as $val){
echo "<option value='{$val["name"]}'>{$val["name"]}</option>";
}
echo "</select>";
?>
As it turned out in the comments you set your default fetch mode with setAttribute(). So you fetch your data as an object and not as an array as it would be normal, with this:
$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
Also a quote from the manual where it says which mode is default:
PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set
So instead of this structure:
Array
(
[0] => Array
(
[id] => 1
[0] => 1
[number] => 3234
[1] => 3234
[text] => sdfdsf
[2] => sdfdsf
[texttext] => sdfsdf
[3] => sdfsdf
)
//...
You have a structure like this:
Array
(
[0] => stdClass Object
(
[id] => 1
[number] => 3234
[text] => sdfdsf
[texttext] => sdfsdf
)
//...
So you need to use -> to access the object property like this:
$val->name
Side Notes:
Also if you would have added error reporting (only while staging, never in production!):
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
?>
You would have received an error like this:
Fatal error: Cannot use object of type stdClass as array
And I would recommend you to enable error mode for your PDO connection (just put it right after the connection statement):
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Then you can also put your db stuff in a try & catch block to catch PDOExceptions:
try {
//db stuff
} catch(PDOException) {
echo $e->getMessage();
}
Given your current code we can state that
you are not doing anything with $genre - you are outputting the <option> elements
there might not be any genres (i.e. $genre is not set)
If 1 is true, Consider putting the explode'd/joined value of $genre in an enclosing <select>docs tag.
In case of 2, the select will be empty. Because your question does not include the specific code for outputting the select, it's hard to say what is really the problem. Your question states "I can't select (drop)" so there might even be JavaScript changing the enabled-attribute of the (if any) outputted select.

PHP - Undefined offset (0) even though it holds a value

I'm trying to work in a CodeIgniter environment and while trying to collect and gather some information into variables I'm getting some PHP NOTICE errors that don't seem right.
Here's the chunk of code where the error(s) occur:
if (empty($events['user'][$user_id])) {
unset($events['user'][$user_id]);
} else {
foreach ($events['user'][$user_id] as $event) {
$events['user'][$user_id]['events']['event_id'] = $event_id = $event['event_id'];
$events['user'][$user_id]['event']['date'] = $this->events_model->getEventDates($event_id);
$events['user'][$user_id]['event']['date'] = $events['user'][$user_id]['event']['date'][0]['date'];
$events['user'][$user_id]['event']['request_title'] = $event['request_title'];
$events['user'][$user_id]['event']['event_status_text'][] = $this->events_model->getEventStatusFromSectionStatuses($event_id);
$request_data = $this->requests_model->getRequestInfo($event['request_id']);
$events['user'][$user_id]['event']['ministry'] = $this->ministries_model->getMinistryTitle($request_data[0]['requesting_ministry']);
// more stuff will go here...
}
$content_data['event_status_text'] = $events['user'][$user_id]['event_status_text'];
$content_data['events'] = $events['user'][$user_id]['complete_events'];
$content_data['totals'] = $events['user'][$user_id]['totals'];
$content_data['updated_events'] = $events['user'][$user_id]['updated_events'];
}
The specific line of the first error is the third line inside the foreach loop that ends with ['date'][0]['date']. It's the [0] that PHP is telling me is undefined. However, if I echo that exact same variable like this:
echo $events['user'][$user_id]['event']['date'][0]['date'];
...it outputs a value as would be expected, which also tells me that the [0] is NOT undefined after all. I'm not actually changing the variable. The only difference is that I'm echoing it instead of assigning it to another variable.
If I use # to ignore it in here, it happens again a few lines later on the line ending with getMinistryTitle($request_data[0]['requesting_ministry']).
Can you see what I'm doing wrong? Let me know if you need to see more of the code.
Here's the getEventDates() code as requested (note this is not my code):
function getEventDates($event_id)
{
$sql = "SELECT date FROM `event_dates` WHERE event_id=? ORDER BY date";
$res = $this->db->query($sql, array($event_id));
return $res->result_array();
}
if I print out $this->events_model->getEventDates($event_id) I get the following:
Array
(
[0] => Array
(
[date] => 2014-05-01
)
[1] => Array
(
[date] => 2014-05-08
)
[2] => Array
(
[date] => 2014-05-15
)
[3] => Array
(
[date] => 2014-05-22
)
[4] => Array
(
[date] => 2014-05-29
)
[5] => Array
(
[date] => 2014-06-05
)
[6] => Array
(
[date] => 2014-06-12
)
)
Hmmm... is it possible that this error is happening because there isn't a direct value contained in [0], but rather another array level? Please note that I did not structure this output. Someone else coded this and it's just my job to come in and work with it.
Without seeing the rest of your code this is confusing:
$events['user'][$user_id]['event']['date'] = $this->events_model->getEventDates($event_id);
$events['user'][$user_id]['event']['date'] = $events['user'][$user_id]['event']['date'][0]['date'];
Why would you be setting $events['user'][$user_id]['event']['date'] in one line and then in the next overriding it again?
My best advice would be to set the first assignment in a variable independent of the array, and then calling that variable for the data:
$event_dates_temp = $this->events_model->getEventDates($event_id);
$events['user'][$user_id]['event']['date'] = $event_dates_temp[0];
And perhaps adding a conditional check to ensure you are setting things that exist:
$event_dates_temp = $this->events_model->getEventDates($event_id);
if (array_key_exists(0, $event_dates_temp)) {
$events['user'][$user_id]['event']['date'] = $event_dates_temp[0];
}
Also, it’s unclear at what point you are doing this:
echo $events['user'][$user_id]['event']['date'][0]['date'];
And what is the output when you do dump like this:
echo '<pre>';
print_r($events['user'][$user_id]['event']['date']);
echo '</pre>';
It happens when you are trying to access a value which is not set for that index, please read this link for more information.
There are two options available:
Ignore these notices by telling the PHP error_reporting to not show notices error_reporting(E_ALL ^ E_NOTICE); but it is a good practice to fix this error by adding a check if a value exists.
Fix the values by isset function to see if the value/index contains any data.
If You hide notice set error_reporting(E_ALL ^ E_NOTICE);
Solution is use isset() to solved this issue.

PHP Fatal error: Cannot use string offset as an array

Facing a weird situation with arrays..
I am using LinkedIn API to get profile info which returns data in two formats..
If user has just one educational item
educations=>education=>school-name
educations=>education=>date
...
If more than one education item
educations=>education=>0=>school-name
educations=>education=>0=>date
...
educations=>education=>1=>school-name
educations=>education=>1=>date
...
Now I am trying to make it consistent and convert
educations=>education=>school-name
to
educations=>education=>0=>school-name
But getting error in code that i believe should work
if(empty($educations['education'][0]['school-name']))
{
$temp = array();
$temp['education'][0]=$educations['education'];
$educations = $temp;
}
This fails for "just one educational item", generates error on the first line for (isset,is_array and empty)
PHP Fatal error: Cannot use string offset as an array in ...
print_r returns
[educations] => Array
(
[education] => Array
(
[id] => 109142639
[school-name] => St. Fidelis College
[end-date] => Array
(
[year] => 2009
)
)
)
Usually you'd write the assignment like this:
$temp = array(
"education" => array($educations['education'])
);
To avoid any issues with indexes. This might also fix yours.
If you're unsure about the contents of $educations['education'][0]['school-name'] you can simply check each part:
if(isset($educations['education'], $educations['education'][0], $educations['education'][0]['school-name']))
This works because isset doesn't behave like a normal function. It takes multiple arguments in a lazy manner.
You want:
if(array_key_exists('school-name',$educations['education']))
{
$educations['education'] = array($educations['education']);
}
Today I experienced the same problem in my application. Fatal error: Cannot use string offset as an array in /home/servers/bf4c/bf4c.php on line 2447
line 2447
if (!isset($time_played[$player]["started"])) {
$time_played[$player]["started"] = $time;
}
$time_played was overwritten elsewhere and defined as a string. So make sure you do use unique variable names.
Here's a tip if you're running through a loop, and it breaks:
if( $myArray != "" ){
// Do your code here
echo $myArray['some_id'];
}

Categories