"undefined variable" error

hmmm. tried posting this eariler but sitepointforum’s databases seem to be ready to check out for the weekend w/a couple of beers lately.
so…Am trying out a phpaccademy tutorial to create a poll.
Am getting this error:

Notice: Undefined variable: polls in C:\xampp\htdocs\pollPhp\index.php on line 11

line 11 has “echo ‘<pre>’, print_r($polls) ,‘</pre>’;”

I have this in the index.php.


<?php
require_once 'init.php';
$pollsQuery = $db->query("
	SELECT id, question
	FROM polls
	WHERE DATE(NOW())BETWEEN starts AND ends
");
while($row = $pollsQuery->fetchObject()){
	$polls[] = $row;
}
echo '<pre>',  print_r($polls) ,'</pre>';
?>

& this in the init.php


<?php
session_start();
$_SESSION['user_id'] = 1;

$db = new PDO('mysql:host=localhost; dbname=website', 'root', '');

?>

Any php expert here could please advs?
thx
D

Not sure why $polls is returning as undefined. Unless there are no records being returned from the query. Did you run the query in a QA? Also, it’s been a while since I worked with PHP, but isn’t the period (.) supposed to concatenate, not the comma (,)?

The only way your $polls variable would be undefined is if the query returned no rows, thereby making the first assignment to the $row variable in the condition of your WHILE loop return false (and so not executing the loop body). So there’s no error in your code; you just simply aren’t finding any results. Good practice, however, would dictate that you first initialise the $polls variable before trying to push elements onto it. Therefore, if no rows were found, you’d be printing out an empty array rather than seeing an ugly error (as is your case). (It’s also marginally faster to push items onto initialised arrays.)

So you may want to consider adding the following line before you while loop:


$polls = array();

You’re correct in that PHP uses the period to concatenate strings, however in this case you can use commas to effectively pass arguments to echo to output to the screen. This makes echo (and print, for that matter) a variadic function (though strictly speaking, echo and print language constructs, not functions - but let’s not go down that road :))

1 Like

Ah… did not know that echo could take parameters. Thanks. :slight_smile:

it seems to be something in how i set up the database. will take a screen shot & post.
thx
D

wow…i love sitepoint but posting here has been a bit of a challenge lately.
Couldn’t attach the screenshot but have it on my google acct.
https://plus.google.com/u/0/photos/114950823627120269815/albums/6056742138651189521/6056742143319490578?pid=6056742143319490578&oid=114950823627120269815

& here is flicker if it is easier
Imgur

Unsigned simply means that the integer must be positive (or 0). Your field is set to be auto-incremented upon new insertions anyway, which means the column will only contained unsigned integers anyway (AUTO_INCREMENT in MySQL starts from 1). I have already outlined the problem in my above post - your query isn’t returning any results.

Your screenshot does, however, show us that the table we are dealing with is called users, and not polls. That’s most probably why you aren’t finding any records…

no…the db connects. but will go double check and see if that is it.
thx
D

i think i am correct.
the code is calling on polls not users.

<?php
require_once 'init.php';
$pollsQuery = $db->query("
	SELECT id, question
	FROM polls
	WHERE DATE(NOW()) BETWEEN starts AND ends
	
");
var_dump($pollsQuery);
while($row = $pollsQuery->fetchObject()){
	$polls[] = $row;
}
echo '<pre>',  print_r($polls) ,'</pre>';
?>

& in init i am accessing the correct db

<?php
session_start();
$_SESSION['user_id'] = 1;

$db = new PDO('mysql:host=localhost; dbname=website', 'root', '');
?>

Could you please execute the following and tell me what is output:


$q = $db->query('show tables');
print_r($q->fetchAll(PDO::FETCH_ASSOC));

I tried but am not sure where i should have entered the code.

<?php
require_once 'init.php';
$pollsQuery = $db->query("
	SELECT id, question
	FROM polls
	WHERE DATE(NOW()) BETWEEN starts AND ends
");
var_dump($pollsQuery);
	while($row = $pollsQuery->fetchObject()){
		$polls[] = $row;
		$q = $pdo->query('show tables');
	   print_r($q->fetchAll(PDO::FETCH_ASSOC));
}
echo '<pre>',  print_r($polls) ,'</pre>';

?>

I am guessing that is incorrect?

Paste it in after the require statement. The query simply shows the tables you have in your database, which should confirm one of my previous posts that you’re querying the incorrect table.

Array ( [0] => Array ( [Tables_in_website] => polls ) [1] => Array ( [Tables_in_website] => polls_answers ) [2] => Array ( [Tables_in_website] => polls_choices ) [3] => Array ( [Tables_in_website] => users ) ) object(PDOStatement)#3 (1) { ["queryString"]=> string(81) " SELECT id, question FROM polls WHERE DATE(NOW()) BETWEEN starts AND ends " }


Notice:  Undefined variable: polls in C:\\xampp\\htdocs\\pollPhp\\index.php on line 14

Hope this help.
D

Right, so your query isn’t returning any results because it isn’t finding any matches then.

ok so will start from scratch.
however as you can see my php skills are pretty meager right now and i def need to brush up on that little i knew.
can you please tell me brake down that printed row?
i see it recognized that there are the tables i created in the “website” database as it should be. So why is it not reading the questions?
thx
D

If you need all fields of all records returned by a query then you should consider using fetchAll http://php.net/manual/en/pdostatement.fetchall.php to grab all the rows of the result set in one hit.

Before grabbing the result set, add:

$polls=array();

That will set up the $polls variable as an empty array so that any function handed $polls that expects to be given an array to work with won’t generate any error.

Reread my first post to this thread for an explanation as to why you’re receiving the error. At the moment, your query is not finding any results because the WHERE clause in your SQL statement has specified a condition that doesn’t match any rows in your table.

As evidence of this, execute the following code snippet in place of your previous one (here):

<?php
require_once 'init.php';
$pollsQuery = $db->query("
  SELECT id, question
  FROM polls
");

$polls = array();
while($row = $pollsQuery->fetchObject()){
    $polls[] = $row;
}
echo '<pre>',  print_r($polls) ,'</pre>';

I’ve simply omitted your WHERE clause condition and put in an empty definition for your $polls variable (as said in my initial post). You should now see results and no errors.

2 Likes

ok thx. back to coding.
D

Thank you tpunt that workd and it returned the two test questions i had

but i still don’t understand why it was “unassigned” i guess. i re read several time your answer.

but i don’t understand why the query wouldn’t return the rows. everything connected. the rows are there. w/auto increments.
Just trying to understand this.
thx
D