gpt4 book ai didi

PHP数组循环迭代并将获取的结果放入MySQL表中

转载 作者:行者123 更新时间:2023-11-29 11:37:14 26 4
gpt4 key购买 nike



我是一名初学者,在发布之前在这里阅读了很多帖子,因为无论我尝试过什么,都无法做我需要做的事情..所以这就是我所做的:
1.通过以 ASC 和 DESC 模式排序对数据库运行 mysql 查询,并获取每种类型 20 条记录,我想采用 3 个特征:term、termid 和 currentRank。
2.然后我用 mysqli_fetch_array 获取这些
3.然后我需要将这 20 个结果存储在临时表中,我想是通过某种循环。

到目前为止,我能够迭代这些值并打印它们,但我在 While 循环中运行查询以在临时表中输入当前值时遇到问题。这是我的应用程序这部分的 PHP:

<?php
$conn=mysqli_connect("localhost","root");
$db_select=mysqli_select_db($conn,"irdb");

//select a random logo from db
$query = mysqli_query($conn,"SELECT logo, companyid FROM company ORDER BY RAND() LIMIT 1");

$row = mysqli_fetch_array($query);
$image = mysqli_real_escape_string($conn,$row[0]);
$compID = mysqli_real_escape_string($conn,$row[1]);

// create new term temporary table newtermlist
$newtermlist = mysqli_query($conn,"CREATE TABLE IF NOT EXISTS irdb.newtermlist (
`newtermid` INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`origtermid` INT(10),
`companyid` INT(20),
`term` VARCHAR(50),
`currentRank` decimal(50,0))");

// sort terms for the random company by highest ranked values
$highestRankTerms = mysqli_query($conn, "SELECT term, currentRank, termid FROM ranks_test
WHERE companyID='$compID'
ORDER BY currentRank DESC
Limit 20");

$highestRow = mysqli_fetch_array($highestRankTerms);
$highestTerm = mysqli_real_escape_string($conn,$highestRow[0]);
$highestCurrentRank = mysqli_real_escape_string($conn,$highestRow[1]);
$highestTermID = mysqli_real_escape_string($conn,$highestRow[2]);

while ($row = mysqli_fetch_array($highestRankTerms,MYSQL_ASSOC)){
printf("<br> term: %s | currentRank: %s | termid: %s", $row["term"], $row["currentRank"], $row["termid"]);
// I need to RUN the UPDATE QUERY below:
// $insertInNewtermlist = mysqli_query($conn,"INSERT INTO `irdb`.`newtermlist` VALUES ('','$compID','$highestTerm','$highestCurrentRank')");
}

?>

当我打印时,我得到以下信息:

enter image description here

所以它部分有效.. 奇怪的是,有时当我尝试不同的事情时,它不会给我任何错误,但表中没有记录,或者最多有 20 个术语中的两个。

我真的很感谢对此的帮助,因为我尝试了我能做的一切,但考虑到我是自学的事实,我可能不知道可能有帮助的东西。

谢谢,阿尼

最佳答案

向您的代码添加错误检查和结果检查:

$query_text = "SELECT logo, companyid FROM company ORDER BY RAND() LIMIT 1";
if ($query = mysqli_query($conn,$query_text)) {

// If no errors occured then check that there are rows in the result:
if ($row = mysqli_fetch_array($query)) {
// We have at least one row then go on
.......
}
else {
echo 'No rows to fetch!';
}
// Don't forget to free results if you do not need them later
mysqli_free_result($query);
}
else {
echo 'Error in your query :'.$query_text;
}

在代码中调用 mysqli_querymysqli_fetch_array, musqli_fetch_assoc 的地方放置类似的检查。现在您将确保查询正确并且结果包含一些要处理的数据。否则,您的输出将会收到错误消息。

关于PHP数组循环迭代并将获取的结果放入MySQL表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36377525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com