数据库未更新值

时间:2016-03-30 01:57:06

标签: php mysql

我有一个表单,每个用户只能有一条记录。我用来确定用户是否有先前提交的条件是由于某些原因而不是写入数据库。任何帮助是极大的赞赏。

以下是代码:

<?php

    $user_id = $_SESSION['user_id'];
    $anthem1 = null;
    $cointoss2 = null;
    $firstscore3 = null;

    //$query

    $query  = "SELECT * ";
    $query .= "FROM mypicks ";
    $query .= "WHERE user_id = {$user_id} ";
    $result = mysqli_query($connection, $query);

        if (isset($result)) {

            //existing submission -  this is breaking it    
            if (isset($_POST['submit'])) {


                if (isset($_POST['anthem1'])) {
                     $anthem1 = $_POST['anthem1'];
                }       

                if (isset($_POST['cointoss2'])) {
                     $cointoss2 = $_POST['cointoss2'];
                }       

                if (isset($_POST['firstscore3'])) {
                     $firstscore3 = $_POST['firstscore3'];
                }   

                $query  = "UPDATE mypicks SET";
                $query .= "anthem1 = '{$anthem1}', ";
                $query .= "cointoss2 = '{$cointoss2}', ";
                $query .= "firstscore3 = '{$firstscore3}' ";
                $query .= "WHERE user_id = {$user_id} ";
                $result = mysqli_query($connection, $query);
            }

            }else{

            //new submission    
            if (isset($_POST['submit'])) {


                if (isset($_POST['anthem1'])) {
                     $anthem1 = $_POST['anthem1'];
                }       

                if (isset($_POST['cointoss2'])) {
                     $cointoss2 = $_POST['cointoss2'];
                }       

                if (isset($_POST['firstscore3'])) {
                     $firstscore3 = $_POST['firstscore3'];
                }   

                $query = "INSERT INTO mypicks (";
                $query .= " user_id, anthem1, cointoss2, firstscore3";
                $query .= ") VALUES (";
                $query .= "  '{$user_id}', '{$anthem1}', '{$cointoss2}', '{$firstscore3}'";
                $query .= ")";
                $result = mysqli_query($connection, $query);

                }   
            }
?>

2 个答案:

答案 0 :(得分:0)

根据https://secure.php.net/manual/en/mysqli.query.php

  

失败时返回FALSE。对于成功的SELECT,SHOW,DESCRIBE或EXPLAIN查询,mysqli_query()将返回一个mysqli_result对象。对于其他成功的查询,mysqli_query()将返回TRUE。

所以isset($result)永远都是真的。要查看$result是否为空,请使用$result -> num_rows

答案 1 :(得分:0)

首先,您在SET

之后错过了一个空格
            $query  = "UPDATE mypicks SET";// Concats as SETanthem1
            $query .= "anthem1 = '{$anthem1}', ";
            $query .= "cointoss2 = '{$cointoss2}', ";
            $query .= "firstscore3 = '{$firstscore3}' ";
            $query .= "WHERE user_id = {$user_id} ";

其次,根据v7d8dpo4所说的内容,你会想要做一些像$ result-&gt; num_rows这样的事情,或者你是否喜欢fetch和rowCount。但这与您的更新问题无关

第三,您可以通过简单地通过phpmyadmin的UI或任何您喜欢的内容测试查询来防止此类错误