PHP MySQL不使用子字符串执行更新

时间:2018-06-25 11:38:26

标签: php mysql sql-update substring

我遇到了PHP的问题,该问题无法在我的脚本中执行一个查询。 SQL查询在我的MYSQL控制台中运行良好,但是没有任何反应。 Year列保持为NULL:

$UpdateYear='UPDATE `pat` SET `Year` = SUBSTRING(`Prepa`,7,4)';
mysqli_query($connWarehouse,$UpdateYear) or   die(mysqli_error($connWarehouse)); 

我不知道我在做什么错。这是完整的脚本:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$db="datawarehouse";

// Create connection
$connWarehouse = new mysqli($servername, $username, $password, $db);

// Check connection
if ($connWarehouse->connect_error) {
    die("Connection failed: " . $connWarehouse->connect_error);
}
$UpdateYear='UPDATE `pat` SET `Year` = SUBSTRING(`Prepa`,7,4)';
    mysqli_query($connWarehouse,$UpdateYear) or   die(mysqli_error($connWarehouse));

mysqli_close($connWarehouse));
?>

1 个答案:

答案 0 :(得分:0)

我终于设法解决了。我不知道这是否是正确的方法。我必须打开与数据库的新连接才能执行。

alter.php:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$db="datawarehouse";

// Create connection
$connWarehouse = new mysqli($servername, $username, $password, $db);

// Check connection
if ($connWarehouse->connect_error) {
    die("Connection failed: " . $connWarehouse->connect_error);
}
$AddYear='ALTER TABLE `pat` ADD COLUMN `Year` YEAR;';
mysqli_query($connWarehouse,$AddYear) or die(mysqli_error($connWarehouse));

mysqli_close($connWarehouse));
include 'uppat.php';
?>

uppat.php

<?php
require_once 'config-datawarehouse.php';

$UpdateYear='UPDATE `pat` SET `Year` = SUBSTRING(`DatePrepa`,7,4)';

mysqli_query($conn,$UpdateYear) or die(mysqli_error($conn));

mysqli_close($conn);
?>

通过这种方式,它执行了更新查询。