Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Make my query's array's key the ID

So I have this array of images pulling and the array's keys are just 0,1,2,3,4,5.... and whatnot...

How can I make the value in the 'id' column of that table the key, and keep 'link' as the value.

Associative Array, no?

Here is my PHP:

$myImageID = $me['imageid'];

$findImages = "SELECT link FROM images WHERE model_id ='{$me['id']}'";
$imageResult = mysql_query($findImages) or die (mysql_error());

$myImages = array();
while($row = mysql_fetch_array($imageResult)) {
    $myImages[] = $row[0];
}

Here is what I have:

{
 [0] -> "http://website.com/link.jpg"
 [1] -> "http://website.com/li123nk.jpg"
 [2] -> "http://website.com/link3123.jpg"
}

Here is what I want:

{
 [47] -> "http://website.com/link.jpg"
 [122] -> "http://website.com/li123nk.jpg"
 [4339] -> "http://website.com/link3123.jpg"
}
like image 893
Rick Bross Avatar asked May 10 '13 23:05

Rick Bross


People also ask

How to use array_keys () function in PHP?

The PHP array_keys () function accepts an array and returns all the keys or a subset of the keys of the array. $array is the input array. $search_value specifies the value of the keys to search for. $strict if it sets to true, the array_keys () function uses the identical operator (===) for matching the search_value with the array keys.

What is the difference between array_keys () and search_value () in PHP?

The PHP array_keys () function accepts an array and returns all the keys or a subset of the keys of the array. $array is the input array. $search_value specifies the value of the keys to search for.

How do I add an ID to an array in MySQL?

Just select the id and make it the key to the array. It's that simple. FYI, you shouldn't use mysql_* functions in new code.

How to create associative array with key-value pairs in PHP?

PHP offers us a special type of array called an Associative Array that allows us to create an array with Key-Value pairs. The syntax for creating an Associative Array is as follows: The comma after the last Key-Value pair is optional. The Key can be of either integer or string type.


2 Answers

Just select the id and make it the key to the array. It's that simple.

$findImages = "SELECT id, link FROM images WHERE model_id ='{$me['id']}'";
$imageResult = mysql_query($findImages) or die (mysql_error());

$myImages = array();
while($row = mysql_fetch_array($imageResult)) {
    $myImages[$row[0]] = $row[1];
}

FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

You also wide open to SQL injections

like image 109
John Conde Avatar answered Sep 24 '22 02:09

John Conde


  $myImages[$me['id']] = $row[0];
like image 31
user2368299 Avatar answered Sep 23 '22 02:09

user2368299