跳过stmt块

时间:2011-11-19 01:54:13

标签: php insert

我是php的新手,我遇到了一个问题,这个问题已经花费了几个小时的时间进行研究和研究,我在网络的任何地方都找不到类似的东西。

数据库:MyPHPAdmin winserver

目标:在表格“照片”中创建一个新行。获取当前用户的最后一个插入p_id,并通过使用该p_id创建一个新行来更新表accessible_to。 我知道我可以创建一个触发器,不管它不起作用也不知道为什么。用尽了想法。

我在if语句之前简单地打印后发现了什么 if ($stmt = $mysqli->prepare("insert into accessible_to values(?, ?, ?)")) 是它绕过它。

请发表您的建议。 附:我所指的上面的if语句已经以多种方式扭曲,但它不起作用。 连接已导入。

非常感谢你。

 if(!isset($_SESSION["id"])) {
  echo "You are not logged in. ";
  echo "You will be returned to the homepage in 3 seconds or click <a href=\"index.php\">here</a>.\n";
  header("refresh: 3; index.php");
}
else {
  //if the user have uploaded a photo, insert it into database
  if(isset($_POST["ext"])) {  
    //insert into database, note that p_id is auto_increment
    if ($stmt = $mysqli->prepare("insert into photo (ext, owner_id) values (?,?)")) {
      $stmt->bind_param("ss", $_POST["ext"], $_SESSION["id"]);
      $stmt->execute();
      $stmt->close();
      $id = htmlspecialchars($_SESSION["id"]);    
    } 
    //The following function is fetching the last added p_id in PHOTO by the user with the current SESSION
    //Do not simply get the last p_id in PHOTO because someone else might have just added another picture meanwhile
    if ($stmt = $mysqli->prepare("select MAX(p_id) from photo where owner_id = ?")){
      $stmt->bind_param("s", $id);    
      $stmt->execute();
      $stmt->bind_result($p_id);
      if ($stmt->fetch()){
        $p_id = htmlspecialchars($p_id);
      } 
    }
    echo "BEFORE accessible_to insertion";
echo '<br />';

if ($stmt = $mysqli->prepare("insert into accessible_to values(?, ?, ?)")){
    echo "Finally inside accessible_to insertion";
    echo '<br />';
    $stmt->bind_param("iss", $p_id, $id, 'T');
    $stmt->execute();
    $stmt->close();
}
echo "AFTER accessible_to insertion";
echo '<br />';
 }   
     //if not then display the form for posting message
      else {
        echo "Something";

2 个答案:

答案 0 :(得分:0)

您不能对布局进行布尔测试,并期望它返回不同的结果。您要测试的是,如果$ stmt-&gt;执行成功执行或不执行。

$stmt = $mysql->prepare("insert into foo values (?,?)"); 
$stmt->bind_param(1,$f1); 
$stmt->bind_param(2,$f2);

if ($stmt->execute()) { 
... worked 
} else {
... fubar
}

答案 1 :(得分:0)

你必须先调用mysqli :: connect($ server,$ user,$ pw,$ db)。最好的方法是构建一个像:

这样的对象
$connection = new mysqli($server, $user, $password, $db);
    if ($connection->errno) 
    {
        echo "Connection failed";
        echo $this->connection->error;
    } 
    else  
    {                                                                                    
        $stmt = $connection->prepare("insert into photo (ext, owner_id) values (?,?)")) {
  $stmt->bind_param("ss", $_POST["ext"], $_SESSION["id"]);
  $stmt->execute();
  $stmt->close();

    }