1

I would like to add results into array and print on screen. Here's my code and nothing is printing...could someone help me take a look.

include('config.php');

$con = mysql_connect($host, $username, $password);
if (!$con){
    die('Could not connect: ' . mysql_error());
}

mysql_select_db('members', $con) or die(mysql_error()) ;

$sql = "SELECT * FROM people where status like '%married%' "; 
$result = mysql_query($sql);

while($row = mysql_fetch_array($result)){
    $result_array[] = $row['id']; // <-------**here**             
}

return $result_array;       

echo($result_array);
mysql_close($con);

2 Answers 2

5

You're doing a return before you do the echo/mysql_close, so the echo/close calls never get executed. Unless you've got more code around this snippet, there's no point in having that return call, as you're not actually in a function, so the return is effectively acting as an "exit()" call, since you're already at the top of the execution stack.

Sign up to request clarification or add additional context in comments.

1 Comment

Not to mention using echo on arrays won't give you much.
2

Firstly, change:

mysql_select_db(mtar, $con) or die(mysql_error());

To:

mysql_select_db('mtar', $con) or die(mysql_error());

Then remove return $result_array; - you don't need it and when used outside of a function it just halts execution of the script.

Finally, change

echo($result_array);

to:

print_r($result_array);

EDIT: Some additional thoughts:

You don't need parentheses around the argument to echo - it's actually more efficient to leave them out: echo $var; is quicker than echo($var);

If you're only ever going to use the id column, then don't select the whole row: use SELECT id FROM instead of SELECT * FROM.

Are you sure you need the wildcards either side of "married"? You may well do (depends on what the possible values of status are), but you probably don't. So

$sql = "SELECT id FROM people where status = 'married' "; 

May be better,

2 Comments

Note: print_r should only be used for debugging purposes.
@daiscog - Thanks for that - it stopped me from cursing myself :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.