使用关系数据库准备语句

时间:2011-07-15 19:57:01

标签: php mysql relational-database prepared-statement

我可以使用一些关于如何更改此查询的帮助

$query = mysql_query("SELECT M.msg_id, M.uid_fk, M.message, M.created, U.username FROM messages M, users U  WHERE M.uid_fk=U.uid and M.uid_fk='$uid' order by M.msg_id desc ")

进入准备好的声明。我不确定mysqli_stmt_bind_param()会发生什么。 这就是我到目前为止所做的:

$stmt = mysqli_prepare($link, "SELECT M.msg_id, M.uid_fk, M.message, M.created, U.username FROM messages M, users U  WHERE M.uid_fk=? and M.uid_fk=? order by M.msg_id desc")) {


mysqli_stmt_bind_param($stmt, "s,s", $uid,$uid); 

我知道$ uid,$ uid是不对的,如何更改M.uid_fk = U.uid和M.uid_fk =' $ uid在bind_para中工作。

由于

1 个答案:

答案 0 :(得分:2)

您只需要绑定实际计划传入的内容,这样您的查询几乎保持不变:

$stmt = mysqli_prepare("SELECT M.msg_id, M.uid_fk, M.message, M.created, U.username FROM messages M, users U  WHERE M.uid_fk=U.uid and M.uid_fk= ? order by M.msg_id desc");

mysqli_stmt_bind_param($stmt, "s", $uid);

当你有多个参数时,绑定类型不是以逗号分隔的,所以如果它看起来像这样:

 mysqli_stmt_bind_param($stmt, "sss", $uid, $someString, $someOtherString);

最后,如果你真的应该使用PDO。 Mysqli更难处理,尤其是准备好的陈述。例如,这是php.net手册中的Prepared语句示例:

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City WHERE CountryCode = ? ORDER by ID DESC LIMIT 150,5";

// you can only bind by reference so we have to do this... and it gets really annoying!
$code = 'US'; 

if ($stmt = $mysqli->prepare($query)) {

    $stmt->bind_param($stmt, 's', $code);

    /* execute statement */
    $stmt->execute();

    /* bind result variables  - we have to do this as well with is really annoying! */
    $stmt->bind_result($name, $code);

    /* fetch values */
    while ($stmt->fetch()) {
        printf ("%s (%s)\n", $name, $code);
    }

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

对PDO做同样的事情:

try {

  $pdo = new PDO("mysql:host=localhost;dbname=mydb", "my_user", "my_password");
} catch(PDOException $e) {
  printf("Connect failed: %s\n", $e->getCode());
  exit();
}

$query = "SELECT Name, CountryCode FROM City WHERE CountryCode = ? ORDER by ID DESC LIMIT 150,5";

    // when you call prepare you can bind all the vairables immediately
    // or you can do it ehn you call PDOStatement::execute()

    if ($stmt = $pdo->prepare($query, array('US')) {


        /* execute statement */
        // if we wanted to bind params at execution time we could use
        // $pdo->execute(array('US'));
        $stmt->execute();


        /* fetch values */
        while (false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            printf ("%s (%s)\n", $row['Name'], $row['Code']);
        }

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

现在,如果您希望绑定到结果或参数的引用变量,您仍然可以使用PDO执行此操作,但我发现它更容易,更灵活,不这样做。所以真的是灵活性。您可以使用简单的过程来实现简单的操作,或者在需要时使用更复杂的过程。