0

Simple question (I think).

I have the below PHP / MySQL script:

$risksql="select risk from jobsrisks where job='$job'";
$executerisks=mysql_query($risksql);
$test=mysql_fetch_array($executerisks);
$riskrows=mysql_num_rows($executerisks);

I want to print the values of the array (for testing), with code:

print_r($test);

This produces the below output:

The query, in php actually outputs 3 records, not just one that is repeated. Any ideas whay I am doing incorrectly? where are the other records and why not in the array? is mysql_fetch_array the correct code to use?

I then want to then use the PHP array in another mysql query:

$ids = join(',',$test);   
$sql = "SELECT * FROM table WHERE risk IN ($ids)"; 

Would this then be correct?

Help is appreciated as always.

Thanks, R

2
  • 2
    It may not help answer your question, but you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article. Commented Aug 14, 2012 at 14:05
  • If there was ever a job risk it's using mysql_query. This kind of code will eventually get you fired. Commented Aug 14, 2012 at 14:22

2 Answers 2

2

you need to fetch each row, ie:

while ($row = mysql_fetch_assoc($result)) {
    echo $row['firstname'];
    echo $row['lastname'];
    echo $row['address'];
    echo $row['age'];
}

check the manual

$ids = join(',',$test);   
$sql = "SELECT * FROM table WHERE risk IN ('$ids')"; 

almost right. don't forget about quotes

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

2 Comments

Quotes don't matter. SQL escaping does.
$ids = join(',',$test); $sql = "SELECT * FROM table WHERE risk IN ($ids)"; - in first it won't work because of <'>; - and yes, you are right; there must be escaping, like mysql_real_escape. And even more, it is better to use PDO. to be more secure, if for some reason PDO is not an option, at least use mysqli drive instead of mysql;
0

why not join the selects?

$sql = "SELECT * FROM table WHERE risk IN (SELECT risk FROM jobsrisks WHERE job='$job')"; 

Comments

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.