PHP 代码在 PHP CLI 中不起作用

标签 php mysql command-line-interface

我使用名为 test.php 的数据库连接编写了 php 代码,如下所示:

<?
$mysqli = new mysqli("localhost","root","","monster");

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

/* return name of current default database */
if ($result = $mysqli->query("INSERT INTO `earth` (`monster_id`, `type`, `name`) VALUES
(NULL, 'defender', 'tortoise')
")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}
$mysqli->close();
?>

当我通过浏览器调用http://localhost/learn/test.php并将数据插入到我的数据库时,它就可以工作

但是当我在 PHP CLI 中运行时

php -r '    $mysqli = new mysqli("localhost","root","","monster");

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

    /* return name of current default database */
    if ($result = $mysqli->query("INSERT INTO `earth` (`monster_id`, `type`, `name`) VALUES
    (NULL, 'defender', 'tortoise')
    ")) {
        $row = $result->fetch_row();
        printf("Default database is %s.\n", $row[0]);
        $result->close();
    }
    $mysqli->close();'

没有插入数据。 现在将我的测试更新为 eval($code);在 Windows 中似乎还可以,但在 LINUX 中则不然

最佳答案

试试这个

php -r '    $mysqli = new mysqli("localhost","root","","monster");

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

    /* return name of current default database */
    if ($result = $mysqli->query("INSERT INTO `earth` (`monster_id`, `type`, `name`) VALUES
    (NULL, \'defender\', \'tortoise\')
    ")) {
        $row = $result->fetch_row();
        printf("Default database is %s.\n", $row[0]);
        $result->close();
    }
    $mysqli->close();'

关于PHP 代码在 PHP CLI 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21426699/

相关文章:

php - 查询异常 Laravel : Driver not found

php - 我如何在 innerhtml 中使用 ajax 和 php 更新 mysql 数据库

python - 使用 Python 创建旧式控制台表单

http - 使用来自文件的发布数据向 cURL 发送请求

c++ - 在 Windows 中删除文件时 CMD 和 PowerShell 有什么区别?

php - 创建数组而不是重复函数

php - 显示ACF的中继字段

php 从 mysql 中选择并接收数据类型

php - mysql conditional "not_in"based on another value to parse array into query

升级到 Snow Leopard 后的 MySQL gem 问题