0

I have a database structure that looks like the following:

enter image description here

I am trying to store the prices as a variables so that if I reference cage_linear_feet it will display 225.

I have tried the following code:

   $sql  = "SELECT * from pricing WHERE region = '$region' ";

   $result = mysqli_query($conn, $sql);

   while($rows=mysqli_fetch_assoc($result)){

   $test[] = array($rows['field']=>$rows['price']);

   }

   print_r ($test); 

This displays the following:

Array ( [0] => Array ( [cage_linear_feet] => 225 ) [1] => Array ( [cage_doors] => 1800 ) )

How do I access the "225" and "1800" values ensuring that if more records are added to the db it will still pick up the correct records. E.g as the $test1 which is cage_doors may change if records are added.

3 Answers 3

2

My opinion is that there is no point in wrapping the key-value pairs in their own separate arrays. I would change this line:

$test[] = array($rows['field']=>$rows['price']);

to this:

$test[$rows['field']] = $rows['price'];

The data association will be maintained in the key=>value pairs of one associative array ($test). So echo $test['cage_linear_feet'] ---> 225

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

2 Comments

Brilliant! Thanks
Sure, glad I could help!
1

If you want to set field as the array-key

$sql  = "SELECT * from pricing WHERE region = '$region' ";
$result = mysqli_query($conn, $sql);

while($rows=mysqli_fetch_assoc($result)){
 $test[$rows['field']] = $rows['price']);
}
print_r ($test);

No you should be able to reference by field like so:

echo $test['cage_doors'];
// returns 1800

Comments

0

Is the column 'field' unique? If so, do this:

while($rows=mysqli_fetch_assoc($result)){
    $test[$rows['field']] = $rows['price'];
}

This will set the key in the array to the field, i.e.

Array('cage_doors' => 1800)

If its not unique, I recommend doing something like:

while($rows=mysqli_fetch_assoc($result)){
    $test[$rows['field'] . '_' . $rows['pricing_id']] = $rows['price'];
}

This will set the key in the array to the field and the pricing id, which makes it unique, i.e.

Array('cage_doors_2' => 1800)

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.