简体   繁体   English

查询包含变量时未检索PHP / Javascript + MySQL数据

[英]PHP/Javascript + MySQL data is not being retrieved when query has variables

So I was trying to make a simple login with PHP. 所以我试图用PHP进行简单的登录。 I can retrieve rows just fine but in this specific case there seems to be a problem in getting the data I needed: 我可以很好地检索行,但是在这种特定情况下,获取所需数据似乎存在问题:

When I execute a query with the condition in the WHERE clause via a variable, I never get the data from the column. 当我通过变量使用WHERE子句中的条件执行查询时,我永远不会从列中获取数据。 I don't get an empty set either. 我也没有空集。

I tested the connection was just fine because when I override the variable inside the method the result returns just fine. 我测试了连接是否正常,因为当我在方法中覆盖变量时,结果将返回正常。

For instance, when I do this: 例如,当我这样做时:

$sql = "SELECT name FROM customers WHERE email='" . $email . "'";
$result = $mysql->executeSql($conn, $sql);

if(!empty($result)){
    while($row = mysqli_fetch_array($result)){
        echo  $row['name'];
    }
}else{
    echo "EMPTY SET";
}

It doesn't return anything at all. 它根本不返回任何东西。

But if I do this: 但是,如果我这样做:

$email = 'richardgwapo@gmail.com';
$sql = "SELECT name FROM customers WHERE email='" . $email . "'";
$result = $mysql->executeSql($conn, $sql);

if(!empty($result)){
    while($row = mysqli_fetch_array($result)){
        echo  $row['name'];
    }
}else{
    echo "EMPTY SET";
}

It fetches the data just fine. 它可以很好地获取数据。 I wonder what is the cause of this. 我想知道是什么原因造成的。 I already tried checking the $email data type via the gettype() method and it says it's a string. 我已经尝试通过gettype()方法检查$ email数据类型,它说这是一个字符串。 I also tried trimming it before passing it on to the query but to no avail as well. 在将其传递给查询之前,我也尝试过修剪它,但是也无济于事。

What could possibly be the cause of this? 这可能是什么原因? Here is my entire sample code for the test login: 这是我用于测试登录的整个示例代码:

<HTML>
<HEAD>
    <?php
        function verifyLogin($email, $passwd){
            require('MySQL.php');

            $mysql = new MySQL;

            $conn = $mysql->connectToMysql("127.0.0.1", "root", "", "fivestarhotel");
            $sql = "SELECT name FROM customers WHERE email='" . $email . "'";
            $result = $mysql->executeSql($conn, $sql);

            if(!empty($result)){
                while($row = mysqli_fetch_array($result)){
                    echo  $row['name'];
                }
            }else{
                echo "EMPTY SET";
            }
        }
    ?>

    <SCRIPT>
        var email = "";
        var passwd = "";

        function buttonPressed(){
            email = document.getElementById("tEmail").value;
            passwd = document.getElementById("tPasswd").value;

            document.write("<?php verifyLogin('" + email + "','" + passwd + "');?>");
        }
    </SCRIPT>
</HEAD>
<BODY>
    <INPUT type="text" id="tEmail" /> <BR/>
    <INPUT type="password" id="tPasswd" /> <BR/>
    <INPUT type="button" value="Go" onclick="buttonPressed()"/>
</BODY>
</HTML>

And here is the MySQL.php for the abstraction of the connection and query execution: 这是用于连接和查询执行抽象的MySQL.php:

<?php
class MySQL{
    var $conn;

    function connectToMySql($servername, $username, $password, $dbName){            
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbName);

        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        return $conn;
    }

    function executeSql($conn, $sql){           
        $result = mysqli_query($conn,$sql);
        return $result;
    }
}
?>

Sample database (please don't mind the empty password yet): 示例数据库(请不要介意空密码):

mysql> select * from customers;
+----+------------------------+-------------+---------------------------+---------+
| id | name                   | contact     | email                     | password |
+----+------------------------+-------------+---------------------------+----------+
|  2 | Percival M. Micael Jr. | 09000000000 | percival.micael@yahoo.com |          |
|  3 | Richard Traballo       | 09000000000 | richardgwapo@yahoo.com    |          |
|  4 | Richard Gwapo          | 09000000000 | richardgwapo@gmail.com    |          |
|  5 | Darrel Ayien           | 09000000000 | darrelayien@yahoo.com     |          |
|  6 | Dummy                  | 09000000000 | dummy@dummy.com           |          |
|  7 | Dummy2                 | 09000000000 | dummy2@dummy2.com         |          |
|  8 | Dummy3                 | 09000000000 | dummy3@dummy3.com         |          |
|  9 | Dummy4                 | 09000000000 | dummy4@dummy4.com         |          |
+----+------------------------+-------------+---------------------------+----------+
8 rows in set (0.00 sec)

You can't do something like this. 你不能做这样的事情。

<SCRIPT>
    var email = "";
    var passwd = "";

    function buttonPressed(){
        email = document.getElementById("tEmail").value;
        passwd = document.getElementById("tPasswd").value;

        document.write("<?php verifyLogin('" + email + "','" + passwd + "');?>");
    }
</SCRIPT>

Javascript is client side and PHP is server side. Javascript是客户端,PHP是服务器端。 Your javascript code only write this line <?php verifyLogin('" + email + "','" + passwd + "');?> in your HTML page. 您的javascript代码仅在HTML页面中写以下行<?php verifyLogin('" + email + "','" + passwd + "');?>

You need use at least Ajax. 您至少需要使用Ajax。 Check this: 检查一下:

Using ajax to send form data to php 使用Ajax将表单数据发送到php

How to send data to php file using ajax 如何使用ajax将数据发送到php文件

http://www.ajax-tutor.com/post-data-server.html http://www.ajax-tutor.com/post-data-server.html

you must use AJAX in this case. 在这种情况下,您必须使用AJAX。 Send the variable name emailid values from the html to another php through ajax as request. 根据要求通过ajax将变量名emailid值从html发送到另一个php。 In php, get the emailid variable value and there run your sql query to to get other required details. 在php中,获取emailid变量值,然后在其中运行sql查询以获取其他必需的详细信息。 Store the result in a php variable, echo it from the php and receive it in the javascript using ajax response. 将结果存储在php变量中,从php中回显它,并使用ajax响应在javascript中接收它。 for more info about ajax, visit this http://www.w3schools.com/ajax/ajax_xmlhttprequest_response.asp 有关ajax的更多信息,请访问此http://www.w3schools.com/ajax/ajax_xmlhttprequest_response.asp

Here is code I've used in the past... 这是我过去使用的代码...

<div id="form-login">
  <form action="reload()" method="post">   
    <fieldset>
      <legend>Please Log In</legend>
      <div id="form-error"></div>
      <div class="form-row1">
        <label for="user" class="required">User:</label>
        <input name="user" type="text" id="user" maxlength="50" />
      </div>
      <div class="form-row2">
        <label for="password" class="required">Password:</label>
        <input type="password" name="password" id="password" maxlength="50">
      </div>
      <div class="form-row2 text-right" style="margin-right: 3px;">
        <input id="submit"  class="submit-button" type="submit" name="Submit" value="Submit" >
        <input id="cancel"  class="submit-button" type="button" value="Cancel" >
      </div>
    </fieldset>
  </form>
</div>

and elsewhere in JavaScript: 以及JavaScript中的其他地方:

  // process the login via ajax
    $('#submit_login').click(function () {
        $('#form-error').hide();
        $('#submit').hide();
        $.ajax({
            type: 'POST',
            url: './php/login.php',
            data: 'email_address=' + $('#email').val() + '&password=' + $('#password').val(),
            dataType: 'json',
            success: function (data) {
                if (data.status == -1) {
                    $('#form-error').html(data.msg).slideDown('slow');
                } else if (data.status == 0) {
                    window.location.replace(data.url);  
                }
                $('#submit').show();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#form-error').html('Oops, Functional Error').slideDown('slow');
                $('#submit').show();
            }
        });
        return false;
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM