0

I'm looking to loop the following script, as to save lines of code, and manual hardcoding. The script pulls specific values from my database and assigns them to variables that are used across my website.

    $w1001a = $conn->query("SELECT columnB FROM table WHERE columnA='w1001a' limit 1")->fetch_object()->content; 
    $w1001b = $conn->query("SELECT columnB FROM table WHERE columnA='w1001b' limit 1")->fetch_object()->content; 
    ....
    $w1025b = $conn->query("SELECT columnB FROM table WHERE columnA='w1001b' limit 1")->fetch_object()->content; 

Thanks in advance!

1
  • Maybe you need to use a IN statement or use a regex for columnA? Commented Mar 13, 2014 at 3:35

1 Answer 1

1

Don't loop the query, use one query to get all the info.

The below is just dummy code:

$stmt = $conn->query("SELECT columnA, columnB FROM table WHERE columnA IN ('w1001a', 'w1001b', ...)");
$result = array();
while ($obj = $stmt->fetch_object()) {
  $result[$obj->columnA] = $obj->columnB;
}
Sign up to request clarification or add additional context in comments.

2 Comments

The query might need a first/one-in-group (i.e. to cover the limit 1), but this is generally a much better approach ..
Thanks @xdazz - Now the data is accessible through $result[w1001a], rather than $w1001a. How would I finish this last step?

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.