Quite having a problem here...

I have an array of student numbers put in a variable.
And this variable will be use to an sql query.

sql = "SELECT class FROM tbl_class WHERE studnum = '$array_studnum'";

How can I get that specific student number inside an array for me to use it in a query.

Thanks. Ill wait for your replies : )

Recommended Answers

All 8 Replies

Maybe is not the best solution but here's an example:

	$arr = array('1','2','3','4'); # simple array
	function sql_where($a)
                $b = "";
		$n = count($a) -1;
		for($i = 0; $i <= $n; $i++)
			$b .= ($i == $n) ? "`studnum` = '$a[$i]' " : "`studnum` = '$a[$i]' OR ";
		return $b;

	$where = sql_where($arr);
        include('con.php'); # include connection
	$query = mysql_query("SELECT class FROM tbl_class WHERE " . $where) or die(mysql_error());
	while($row = mysql_fetch_assoc($query))
		echo $row['class'] . "\n";

sql_where() will output something like:

`studnum` = '1' OR `studnum` = '2' OR `studnum` = '3' OR `studnum` = '4'
commented: good code +6

Thanks! your code did help.

I have another problem.
Yes I got the class I want thru that function you gave me.
But how can I display the result like this:

Student - class
Student1 - a
Student1 - b
Student2 - a

thanks for the reply by the way...

If Student will contain a field from another table, for example tbl_students then write:

"SELECT concat(s.firstname,' ',s.lastname) as student, c.class FROM tbl_students s, tbl_class c WHERE s.id = c.studnum and (" . $where . ")"

bye :)

Member Avatar

You can also use IN:

$str = implode("','",$array_studnum);
$sql = "SELECT class FROM tbl_class WHERE studnum IN ('$str')";

OR if all values in array are integers, no need for ':

$numlist = implode(",",$array_studnum);
$sql = "SELECT class FROM tbl_class WHERE studnum IN ($numlist)";
commented: nice! +5

thanks! that little code is SO cool!

Member Avatar

OK, are we solved?

yes : ) thanks!

Member Avatar

OK, mark the thread as solved - the link below the edit box.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.