I use PHP extension pdo_dblib to access MS SQL SERVER. I used this connection:
$pdosql = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
I retrive the data from table:
$sql = 'SELECT cust_id FROM customers ORDER BY cust_id';
$rez = $pdosql->query($sql);
while($arr = $rez->fetch(PDO::FETCH_NUM)){
$sql1 = 'SELECT employee_name FROM employes ORDER BY emplyee_name';
$rez1 = $pdosql->prepare($sql1);
$rez1->bindValue(':id_cust',$arr[0],PDO::PARAM_INT);
$rez1->execute();
$arr1 = $rez1->fetch(PDO::FETCH_NUM);
echo $arr1[0];
}
Instead to show first employee's name for all 20 customers, query return data only for first customer. I found a solution to open a new PDO before while
:
$pdosql = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
And all works fine. Is there another solution?
Because if I have while
in while
, the time to retrieve data is increasing.
If I used this code in mySQL database (with proper connection), all works fine.
It looks like the query inside the loop doesn't include the parameter. Perhaps add "WHERE cust_id = :id_cust" to the query:
$sql1 = 'SELECT employee_name FROM employes WHERE cust_id = :id_cust ORDER BY emplyee_name';
Also, you may be able to optimize your code a bit by making one query the to database using a join. Something like this:
SELECT
B.employee_name
FROM customers A
INNER JOIN employees B
ON A.cust_id = B.cust_id
ORDER BY
A.cust_id
However, I'm also unsure of your database design and not sure how customers and employees are actually related.
我同意,在查询中使用内部联接,在表之间使用一个公共字段,这将更实用,这将向您显示所需的结果,我建议根据经验或您想使用存储过程。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.