2013-02-18 141 views
0

我正在尝试为下面的MySQL查询调整以下代码,但无法解决如何执行此操作。该查询应该只返回一行,并且我想从该行的“代码”列中提取数据,并将其作为变量传递给我的PHP脚本。将MySQL查询返回的单列值传递给PHP脚本

/* prepare statement */ 
if ($stmt = $mysqli->prepare("SELECT Code from Clients where Name='Jane'")) { 
    $stmt->execute(); 

    /* bind variables to prepared statement */ 
    $stmt->bind_result($code); 

    /* fetch values */ 
    while ($stmt->fetch()) { 
     printf($code); 
    } 

    /* close statement */ 
    $stmt->close(); 
} 

回答

1

我认为你一直在http://php.net/manual/en/mysqli.prepare.php的基础上工作。然而,你应该跟进的结合参数,可以过:

/* prepare statement */ 
if ($stmt = $mysqli->prepare("SELECT Code from Clients where Name=?")) { 

    /* bind query parameters to prepared statement */ 
    $stmt->bind_param("s", 'Jane'); 

    $stmt->execute(); 

    /* bind result variables to prepared statement */ 
    $stmt->bind_result($code); 

    /* fetch values */ 
    if ($stmt->fetch()) { 
     printf('Code: %s', $code); 
    } else { 
     print("Client code was not found"); 
    } 

    /* close statement */ 
    $stmt->close(); 
} 

你在这里准备语句,所以你应该单独绑定您的PARAMS。

+0

谢谢,效果很好。 – Nick 2013-02-18 16:36:37

0

转到搭配:

if ($stmt = $mysqli->prepare("SELECT Code from `Clients` where Name = 'Jane' LIMIT 1")) { 
    $stmt->execute(); 
    $stmt->bind_result($code); 
    $stmt->fetch(); 
    $stmt->close(); 
} 

在脚本$code年底将从列Code包含的数据。

0

您可以更改您的代码如下:

$value = $stmt->fetch(); 

此外,如果你知道你想从数据库中的单个值,可以加快它一点点,通过在年底做了'limit 1' sql语句。

0

不要为这样的小事操作浪费太多的代码。看,这几乎是整个屏幕!
如果在整个代码中需要十几个变量,该怎么办?
封装所有的代码放到辅助功能然后调用它在同一行:

$code = $db->getOne("SELECT Code from Clients where Name='Jane'");