最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Select Exists在mysql中总是返回true

运维笔记admin16浏览0评论

Select Exists在mysql中总是返回true

Select Exists在mysql中总是返回true

我正在尝试制作一个登录表单,在此之前我必须先注册用户。但是这段代码总是说该用户已经存在,即使不是这种情况。我在做什么错?

connection.query("select exists (select * from demoApp where username = '" + username + " ')", function (error, result) {
    if (error) {
        LOG.error(error);
        return;
    }
    else {
        LOG.info(result);
        if (result) {
            LOG.info("Username already exists!");
        }

        else {

            connection.query("INSERT INTO demoApp (username, password) VALUES( '" + username + "', '" + password + "')", function (error, result) {
                if (error) {
                    LOG.error(error);

                    return;
                }
                else {
                    LOG.info("Username added.");

                }
            });
        }
    }
});

};

回答如下:

您在问题标题“ MySQL总是返回true ...”中所说的是错误的;您稍后在评论中说MySQL返回0或1

您的JavaScript在逻辑上有缺陷。您是在说if(result),但结果远不只是一个简单的整数0或1,所以说if(result)将有效地测试它是否为null,这永远不会,因此“始终为true”]

您的代码应看起来像这样(我还解决了旧代码容易受到注入黑客攻击的问题:

//alias the result column using AS xxx to make it easier to refer to in js
//ALWAYS use parameters (WHERE username = ?) to pass values from the user into the db
let sql = "select exists (select * from demoApp where username = ?) as userExists";
connection.query(sql, [username],
function (error, result) {
    if (error) {
        LOG.error(error);
        return;
    }
    else {
        LOG.info(result);
        if (result[0].userExists == 1) { //no harm in being explicit. Result is a collection of rows with names of columns, index it to get the first and specify the column (which is really hard to do with name of you don't alias your query result
            LOG.info("Username already exists!");
        }
...
发布评论

评论列表(0)

  1. 暂无评论