Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 未定义偏移量和语法错误,但代码执行正确_Php - Fatal编程技术网

Php 未定义偏移量和语法错误,但代码执行正确

Php 未定义偏移量和语法错误,但代码执行正确,php,Php,阿贾克斯: position.php 传输两个数组($id和$index),元素数相等 ... success: function(data){ console.log(data); } extract($\u POST); 打印(ID); 打印(索引); 对于($i=0;$i查询(“更新“..$table.”SET inde=“..$indexes[$i]”其中id=“..$ids[$i]);//这是第10行 } 代码执行正确,即所有表数据按预期更新,但conso

阿贾克斯:

position.php

传输两个数组(
$id
$index
),元素数相等

... 
success: function(data){
        console.log(data);
    }
extract($\u POST);
打印(ID);
打印(索引);
对于($i=0;$i查询(“更新“..$table.”SET inde=“..$indexes[$i]”其中id=“..$ids[$i]);//这是第10行
}
代码执行正确,即所有表数据按预期更新,但console(列出数组后)显示一些错误:

extract($_POST);

print_r($ids);
print_r($indexes);

for ($i = 0; $i <= count($ids); $i++) {
    $stmt = $db->query("UPDATE " . $table . " SET inde = " . $indexes[$i] . " WHERE id = " . $ids[$i]); // this is line 10
}
数组
(
[0] => 25
[1] => 23
[2] => 18
[3] => 26
[4] => 21
)
排列
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
注意:第10行的D:\matria\s02\admin\position.php中有5个未定义的偏移量
致命错误:未捕获PDOException:SQLSTATE[42000]:语法错误或访问冲突:1064…靠近D:\matria\s02\admin\position.php:10中第1行的“WHERE id=”处

有什么帮助吗?

问题在于您的
for
循环:

    Array
    (
        [0] => 25
        [1] => 23
        [2] => 18
        [3] => 26
        [4] => 21
    )
    Array
    (
        [0] => 0
        [1] => 1
        [2] => 2
        [3] => 3
        [4] => 4
    )

<b>Notice</b>:  Undefined offset: 5 in <b>D:\matria\s02\admin\position.php</b> on line <b>10</b><br />

<b>Fatal error</b>:  Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064... near 'WHERE id =' at line 1 in D:\matria\s02\admin\position.php:10  
然后当
$i
达到5时,它不会尝试执行操作

编辑:

最初的答案解决了您的实际错误,但在修复后仍有一些地方需要重构/改进:

  • 您有一个名为
    $indexes
    的数组,它本身的索引也将索引存储为值。如果问题中没有未提及的反例,那么整个数组是多余的,您可以删除
    $indexes
    ,您可以使用
    $i
    而不是
    $indexes[$i]
  • for循环中的
    $i
    将在每次迭代中计算
    $id
    的数量。在
    for
    之前只计算一次,使用类似于
    $myCount=count($ids)的方法更加优雅;
    然后在
    for
    中使用
    $i<$myCount
    ,只计算一次
建议代码:

for ($i = 0; $i < count($ids); $i++) {
extract($\u POST);
打印(ID);
$myCount=count($id);
对于($i=0;$i<$myCount;$i++){
$stmt=$db->query(“更新“..$table.”SET inde=“..$i.”其中id=“..$ids[$i]);//这是第10行
}
for ($i = 0; $i < count($ids); $i++) {
extract($_POST);

print_r($ids);

$myCount = count($ids);
for ($i = 0; $i < $myCount; $i++) {
    $stmt = $db->query("UPDATE " . $table . " SET inde = " . $i . " WHERE id = " . $ids[$i]); // this is line 10
}