如何在“for”循环的每次迭代中增加mysql中的行?

时间:2014-11-06 06:05:49

标签: php mysql mysqli

我希望我的小脚本能够获取已插入数据库的链接,从该网页获取该文本并将其插入同一行的不同列中。然后在下一行再做一次。我得到了这个"类mysqli的对象无法转换为字符串"错误,但我不知道如何正确表示行号。这是迄今为止我所拥有的。

更新 好的我感谢您的帮助。我想我不清楚这一点。错误消息在显示$query1 = "$conn, SELECT adlink, key FROM usedcars WHERE key = $x";的行上显示 或者至少,这就是现在的说法。我已经尝试了所有建议的解决方案,到目前为止我只是得到了一堆其他错误。

for ($y=1;$y=1201;$y++)
    {
    $x = 1;

    $query1 = "$conn, SELECT adlink, key  FROM usedcars WHERE key = $x";

    $query2 = "$conn, INSERT INTO usedcars (adtext), VALUES ($final_text) WHERE key = $x";

    $link_result = mysqli_query($query1);

    $text_holder = file_get_contents($link_result);
    $final_text = parse_array($text_holder, "postingBody", "<!-- .posting -->");

    mysqli_query($query2);
    echo "<font size='18' color='#FFFF00'>Placing text from $link_result into database</font><br>"; 
    $x++;
    }

我知道它可能很简单......我不像你们那么聪明。

3 个答案:

答案 0 :(得分:1)

首先检查key = $x的所有字段是否都存在

使用update代替insert

WHERE用于过滤现有结果,如@Eliel所说,不要添加新结果......

$query1 = "$conn, SELECT adlink, key  FROM usedcars WHERE key = $x";

$query2 = "$conn, UPDATE usedcars (adtext), VALUES ($final_text) WHERE key = $x";

$link_result = mysqli_query($query1);

如果想要添加新的用途:

$query1 = "$conn, SELECT adlink, key  FROM usedcars WHERE key = $x";

$query2 = "$conn, INSERT INTO usedcars (adtext,***,***) VALUES ($final_text,***,***)"; // provide all necessary fields

$link_result = mysqli_query($query1);

答案 1 :(得分:0)

当您使用$query1 = "$conn, SELECT adlink, key FROM usedcars WHERE key = $x";并将其传递给mysqli_query()时,$conn被假定为字符串,它会尝试将$conn用作字符串。这就是为什么错误来了。

试试这个 -

$query1 = "SELECT adlink, key  FROM usedcars WHERE key = $x";

$query2 = "UPDATE usedcars (adtext), VALUES ($final_text) WHERE key = $x";

$link_result = mysqli_query($conn, $query1);

答案 2 :(得分:0)

这是您的查询

for ($y=1;$y=1201;$y++)
{
$x = 1;

$query1 = "$conn, SELECT adlink, key  FROM usedcars WHERE key = $x";

$query2 = "$conn, INSERT INTO usedcars (adtext), VALUES ($final_text) WHERE key = $x";

$link_result = mysqli_query($query1);

$text_holder = file_get_contents($link_result);
$final_text = parse_array($text_holder, "postingBody", "<!-- .posting -->");

mysqli_query($query2);
echo "<font size='18' color='#FFFF00'>Placing text from $link_result into database</font><br>"; 
$x++;
}

我建议的查询

 $x = 1;//put it before loop, every loop this $x will become one and the incrementation doesn't take effect
for ($y=1;$y=1201;$y++)
{


$query1 = "$conn, SELECT adlink, key  FROM usedcars WHERE key = $x";

$query2 = "$conn, INSERT INTO usedcars (adtext), VALUES ($final_text) ";//remove your where

$link_result = mysqli_query($query1);

$text_holder = file_get_contents($link_result);
$final_text = parse_array($text_holder, "postingBody", "<!-- .posting -->");

mysqli_query($query2);
echo "<font size='18' color='#FFFF00'>Placing text from $link_result into database</font><br>"; 
$x++;
}