简体   繁体   English

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

[英]PHP array iteration in loop and put fetched results in a table with MySQL



I am a beginner and read quite many threads here before posting as whatever i tried, could not do what i need to do.. so here's what I do: 我是一个初学者,在发布之前阅读了很多线程,因为我尝试过的所有内容都无法完成我需要做的事情..所以这就是我的工作:
1. Run a mysql query to DB by sorting in ASC and DESC mode and get 20 records of each type, I want to take 3 features: term, termid and currentRank. 1.通过在ASC和DESC模式下排序对数据库运行mysql查询,并获得每种类型的20条记录,我想采用3个功能:term,termid和currentRank。
2. Then I fetch these with mysqli_fetch_array 2.然后,我使用mysqli_fetch_array获取它们
3. Then I need these 20 results to be stored in a temporary table, I suppose with some sort of loop. 3.然后,我想通过某种循环将这20个结果存储在临时表中。

So far i was able to iterate over the values and print them, but I am having trouble with running a query within the While loop to input the current values in the temporary table. 到目前为止,我能够遍历值并打印它们,但是在While循环中运行查询以在临时表中输入当前值时遇到了麻烦。 Here my PHP for this part of the application: 这是我针对应用程序这一部分的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')");
}

?>

When I print I get the following: 当我打印时,得到以下信息:

在此处输入图片说明

So it works partially.. The strange thing is that sometimes when I try different things, it gives me NO error, but no record is present in the table or at most two terms out of 20. 奇怪的是,有时当我尝试其他操作时,它没有错误,但表中没有记录,或者20条表中最多没有两项。

I would really appreciate help on it, cause i tried everything that I am capable of, but considering the fact that I am self-studying, I probably do not know something that might help. 我会非常感谢您的帮助,因为我尝试了我所能提供的一切,但是考虑到我的自学能力,我可能不知道可能会有所帮助。

Thanks, Ani 谢谢阿妮

Add error checking and result checking to your code: 将错误检查和结果检查添加到您的代码中:

$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;
}   

Put simmilar checks in your code everywhere where you call mysqli_query and mysqli_fetch_array, musqli_fetch_assoc . 在调用mysqli_querymysqli_fetch_array,musqli_fetch_assoc的任何地方的代码中放置simmilar检查。 Now you will be sure the queries are correct and results contain some data to handle. 现在,您将确保查询正确,并且结果包含一些要处理的数据。 Otherwise you will get error messages to your output. 否则,您将获得错误消息到输出。

**** SOLVED **** **** 解决了 ****

So the thing was that I did not see the error message and had a wrong number of columns to insert into, instead of inserting in 5 columns, I was trying to insert in 4. So here's what I added in the while loop: 因此,问题是我没有看到错误消息,并且要插入的列数错误,而不是插入5列,而是尝试插入4。所以这是我在while循环中添加的内容:

while ($row = mysqli_fetch_array($lowestRankTerms,MYSQL_ASSOC)){
    $insertInNewtermlistLOW = mysqli_query($conn,"INSERT INTO `irdb`.`newtermlist` (origtermid,companyid,term,currentRank) VALUES ('".$row["termid"]."','$compID','".$row["term"]."','".$row["currentRank"]."')");

    if(!$insertInNewtermlistLOW) {
        die("error in the insert Query above: " .mysqli_error($conn));
    }
}

Lesson to learn: ALWAYS MAKE SURE TO TEST THE QUERY AND OUTPUT THE ERROR 要学习的课程:务必确保测试查询并输出错误
As soon as I saw the error I knew that to do.. 一看到错误,我就知道要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM