通过1个查询获得许多值

时间:2019-05-26 11:40:07

标签: php sql where

from random import randint
import unittest

class RandomGen:
    def __init__(self):
        self.num = None

    def compute_num(self):
        random = randint(1000, 8876)
        random = list(map(int, str(random)))
        while random[0] == random[1] or random[0] == random[2] or \
              random[0] == random[3] or random[1] == random[2] or \
              random[1] == random[3] or random[2] == random[3]:
            random = randint(1000, 8876)
            random = list(map(int, str(random)))
        num = ""
        self.num = int(num.join(map(str,random)))

class RandomGenTest(unittest.TestCase):

    # It's hard to test random number generators deterministically.
    # Therefore, just repeat it a bunch of times to increase the chance for
    # incorrect results to show up. In this case, 10000 times.

    def test_range(self):
        gen = RandomGen()     
        for i in range(10000):
            gen.compute_num()
            self.assertGreaterEqual(gen.num, 1000)
            self.assertLessEqual(gen.num, 8876)

    def test_duplicates(self):
        gen = RandomGen()     
        for i in range(10000):
            gen.compute_num()
            numbers = list(map(int, str(gen.num)))
            self.assertEqual(len(numbers), len(set(numbers)))

if __name__ == '__main__':
    unittest.main()

+----+-----------+-----+
| ID | name      |price|
+----+-----------+-----+
|  1 |dest_tahiti|  10 |
|  2 |dest_bora  |  20 |
| ...|   ...     | ... | 
+----+-----------+-----+

我想自定义 $price="SELECT price FROM rates WHERE name IN('dest_tahiti','dest_bora', ...) "; $price_prep= mysqli_query($connect,$price); $price_result= mysqli_fetch_array($price_prep); echo $prix_result["price"] //Just display price for dest_tahiti with WHERE = 'dest_tahiti'; echo $prix_result["price"] //Just display price for dest_bora with WHERE = 'dest_bora'; ,用<{1}} 进行相同的查询 >? 你可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您可以在查询中包含名称作为输出。然后,迭代返回的行并构建一个数组,其中索引是名称,值是价格。

$price = "SELECT name, price FROM rates WHERE name IN('dest_tahiti','dest_bora', ...) ";
$price_result = mysqli_query($connect, $price);
$prix_result = [];
while($row = mysqli_fetch_array($price_result, MYSQLI_ASSOC)) {
  $prix_result[ $row['name'] ] = $row['price'];
}

echo $prix_result['dest_tahiti'];
echo $prix_result['dest_bora'];