0

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.
e.g.

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 : )

Edited by rakwel10: n/a

3
Contributors
8
Replies
10
Views
5 Years
Discussion Span
Last Post by diafol
2

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

<?php
	$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'
Votes + Comments
good code
0

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...

0

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 :)

1

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)";

Edited by diafol: n/a

Votes + Comments
nice!
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.