Jump to content

Creating an array


master82

Recommended Posts

I need to create an array from a list of IDs within a database table.

 

The table consists of 3 fileds, a unique ID, a user ID and the last is an int value (item number)

 

eg

1 3 7

2 4 5

3 3 2

etc...

 

How would I go about using this query

 

$query1=mysql_query("SELECT itemnumber FROM table WHERE userid = '{$user}'");

 

Would i be right in thinking I can use:

$array = mysql_fetch_array($query1);

 

to store all the item numbers associated with the user specified in the first query?

Link to comment
Share on other sites

$sql = "SELECT itemnumber FROM table WHERE userid = '{$user}'";
if($result = mysql_query($sql)){
	if(mysql_num_rows($result) > 0){
		while($row = mysql_fetch_assoc($result)){
			$itemnumber[] = $row['itemnumber'];
		}
	}else{
		echo 'not found';
	}
}else{
	echo mysql_error();
}
}

Link to comment
Share on other sites

for that you'd need to echo out the array using a foreach statement.

for example:

$sql = "SELECT ";
foreach($array as $key => $value){
     $sql .= $value . ", ";
}
$sql .= "FROM table WHERE userid = '{$user}'";

 

That's an example. It wont work completely, because you'll have a ',' just before FROM which wont work.

You'd have to check if it's the last one in the array and if so NOT output the ','

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.