简体   繁体   中英

How to select certain fields from table in mySQL using PHP

I'm trying out my hand at php at the moment - I'm very new to it!

I was wondering how you would go about selecting all items from a mySQL table (Using a SELECT * FROM .... query) to put all data into an array but then not displaying the data in a table form. Instead, using the extracted data in different areas of a web page.

For example:

I would like the name, DOB and favorite fruit to appear in one area where there is already say 'SAINSBURYS' section hardcoded into the page. Then further down the next row that is applicable to 'ASDA' to appear below that.

I searched both here and google and cant seem to find an answer to my strange questions! Would this involve running the query multiple times filtering out the sainsburies data and the asda data where ever I wanted to place the relevant

   echo $row['name']." ";
   echo $row['DOB']." "; etc etc

next to where it should go?

I have got php to include data into an array (I think?!)

$query = "SELECT * FROM people"; 

$result = mysql_query($query) or die(mysql_error());

$row = mysql_fetch_array($result) or die(mysql_error());

while($row = mysql_fetch_assoc($result))
{
   echo $row['name']." ";
   echo $row['DOB']." ";
   echo $row['Fruit']." ";
}

?>

Just place this (or whatever your trying to display):

echo $row['name']." ";

Anywhere you want the info to appear. You can place it within HTML if you want, just open new php tags.

<h1>This is a the name <?php echo $row['name']." ";?></h1>

If you want to access your data later outside the while-loop, you have to store it elsewhere.

You could for example create a class + array and store the data in there.

class User {
    public $name, $DOB, $Fruit;
}

$users = new array();

$query = "SELECT * FROM people"; 
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)) {
    $user = new User;
    $user->name = $row["name"];
    $user->DOB = $row["DOB"];
    $user->Fruit = $row["Fruit"];

    $users[$row["name"]] = $user;
}

Now you can access the user-data this way:

$users["USERNAME"]->name

$users["USERNAME"]->DOB

$users["USERNAME"]->Fruit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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