开发者

Declaring variables in PHP query with sub query not working. Undefined index: deviceName

I'm having some issues declaring a value in my php statement. The 2 values outside of the sub query declare fine but the one inside the sub query does not work and gives me Undefined index: deviceName.

    $sql4 = "SELECT endPort, startPort, 
        ( 
            SELECT deviceName
            FROM devices
            WHERE devices.deviceID = patching.endDeviceID
        )
    FROM patching
    WHERE deviceID =  '$deviceID'
    LIMIT 0 , 10"; 

    $query4 = mysql_query($sql4);
    while ($row = mysql_fetch_array($query4))
        {
            $startp = $row['startPort'];
            $endp = $row['endPort'];
            $endname= $row['deviceName'];

            echo '<tr class="logm"><td>'.$startp.'</td><td></td><td>'.$endname.'</td><td></td><td>'.$endp.'</td><td></td></tr>';

        }

Is it possible to declare this value and am i d开发者_如何学编程oing it wrong or is there another way round this issue.


You didn't give the subquery result a name:

SELECT endPort, startPort,
    ( 
        SELECT deviceName
        FROM devices
        WHERE devices.deviceID = patching.endDeviceID
    ) AS deviceName
FROM patching
WHERE deviceID = '$deviceID'
LIMIT 0, 10

Though you should be using joins, not subqueries:

SELECT endPort, startPort, deviceName
  FROM patching
  LEFT JOIN devices ON(devices.deviceID = patching.endDeviceID)
 WHERE patching.deviceID = '$deviceID'
 LIMIT 0, 10


You should use a join for this:

SELECT endPort, startPort, deviceName
FROM patching
LEFT JOIN devices USING (deviceID)
WHERE deviceID = '$deviceID'
LIMIT 0 , 10

Note: If $deviceID is user input, you have to escape it with mysql_real_escape_string or use prepared statements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜