使用数组从数据库中获取数据

时间:2017-05-09 06:25:15

标签: php arrays oop mysqli foreach

我在class.php中有这段代码:

public function selectFrom(){
    $stmt = $this->conn->prepare("SELECT c.* , s.* FROM country c,segments s GROUP BY country") or die($this->conn->error);
    if($stmt->execute()){
        $result = $stmt->get_result();
        return $result;
    }
}

此代码位于index.php

<?php                           
require 'class.php';

$conn = new db_class();
$read = $conn->selectFrom();
while($fetch = $read->fetch_array(MYSQLI_ASSOC)) { 
    ?>
    <tr>                                        
        <td><?php printf($fetch['country']) ?></td>
    </tr>
    <?php
}
?>  

我需要使用数组从国家/地区表中获取数据,并使用数组从表表段中获取数据 有帮助吗?我是新手。谢谢大家

2 个答案:

答案 0 :(得分:1)

fetch_array - mysqli_fetch_array - 将结果行提取为关联行,数字数组或两者

 int main()
{

// The user inputs a string of numbers (e.g. "6 4 -2 88 ..etc") and those integers are then put into a vector named 'vec'.
std::vector<int> vec;

// Converts string from input into integer values, and then pushes said values into vector.
std::string line;
if ( getline(std::cin, line) )
{
    std::istringstream str(line);

    int value;
    str >> value;
    vec.push_back( value );
    while ( str >> value ) 
    {
        vec.push_back( value );
    }
}
// Creating QuickSort object.
QuickSort qSort;
QuickSort *ptrQSort = &qSort;
// Creating new vector that has been 'Quick Sorted'.
int vecSize = vec.size();
std::vector<int> qSortedVec;
qSortedVec = ptrQSort->sortFunc( vec, 0, vecSize-1 );

// Middle, start, and end positions on the vector.
int mid = ( 0 + (vec.size()-1) )  / 2;
int start = 0, end = vec.size() - 1;

// Creating RecursiveBinarySearch object.
RecursiveBinarySearch bSearch;
RecursiveBinarySearch *ptrBSearch = &bSearch;
//bool bS = ptrBSearch->binarySearch( qSortedVec, mid, start, end );
bool bS = ptrBSearch->binarySearch( bSortedVec, mid, start, end );


/*--------------------------------------OUTPUT-----------------------------------------------------------------------*/

// Print out inputted integers and the binary search result.

// Depending on the binary search, print either 'true' or 'false'.
if ( bS == 1 )
{
    std::cout << "true ";
}
if ( bS == 0 )
{
    std::cout << "false ";
}

// Prints the result of the 'quick sorted' array.
int sortedSize = qSortedVec.size();
for ( int i = 0; i < sortedSize; i++ )
{
    std::cout << qSortedVec[i] << " ";
}
std::cout << "\n";


return 0;
}

答案 1 :(得分:0)

您的查询完全错误:

SELECT c.* , s.* FROM country c,segments s GROUP BY country

这里使用JOIN的方法,但查询中没有指定JOIN条件。而GROUP BY country其中country是您的表名。

请先了解基本概念,然后尝试这样复杂的查询。