2014-07-23 107 views
-2

我的表中有很多行。其中一列被称为name。我还有一个名为blog_id的新专栏。我想使每个blog_id这样的:更新每一行的列到新列

$blog_id = strtolower(preg_replace('/-+/', '-', preg_replace('/[^\wáéíóú]/', '-', $name))); 

我已经试过这样:

$con=mysqli_connect("localhost","foo","bar","blog"); 

$fetch = mysqli_query($con,"SELECT name 
FROM entries"); 

foreach($fetch as $name2){ 

$id = strtolower(preg_replace('/-+/', '-', preg_replace('/[^\wáéíóú]/', '-', $name2))); 

$result = mysqli_query($con,"INSERT INTO entries (blog_id) 
VALUES ('$id')"); 

} 
mysqli_close($con); 

但我得到的错误strtolower() expects parameter 1 to be string, array given我在做什么错?

+1

你能分辨出错误怎么说?它说,你给它一个数组,当它预期的字符串?然后你去php.net/preg_replace它说'preg_replace()返回一个数组,如果主题参数是一个数组,否则一个字符串'。仔细阅读,它提到**数组**。 –

回答

1

尝试:

foreach($fetch as $row){ 
    $id = strtolower(preg_replace('/-+/', '-', preg_replace('/[^\wáéíóú]/', '-', $row['name']))); 
    $result = mysqli_query($con,"INSERT INTO entries (blog_id) VALUES ('$id')"); 
} 

你遍历每一行,每一行是您在查询中选择是什么,在这种情况下,“名”的数组,我想你刚才在期待环一个名称数组,而不是具有名称的行。

编辑

我可能会做这种方式,以确保太:

while($row = mysqli_fetch_array($fetch)){ 
    $id = strtolower(preg_replace('/-+/', '-', preg_replace('/[^\wáéíóú]/', '-', $row['name']))); 
    $result = mysqli_query($con,"INSERT INTO entries (blog_id) VALUES ('$id')"); 
} 

EDIT 2

而不是插入的行,就应该对其进行更新。 在这种情况下,你也应该得到行的ID,所以你的SELECT代码将是:

$fetch = mysqli_query($con,"SELECT id, name FROM entries"); 

那么你应该做这样的事情:

while($row = mysqli_fetch_array($fetch)){ 
    $id = strtolower(preg_replace('/-+/', '-', preg_replace('/[^\wáéíóú]/', '-', $row['name']))); 
    $result = mysqli_query($con,"UPDATE entries SET blog_id='".$id."' WHERE id=".$row['id']); 
} 
+0

这只是似乎创建新的行而不是更新.. – maxisme

+0

哦,对不起,我希望你想这样做,因为你的代码中的INSERT语句,我会为你更新我的答案。 –

+0

我得到错误:'mysql_fetch_array()期望参数1是资源,给定的对象需要'mysqli_fetch_array'而不是! – maxisme