Announcement

Collapse
No announcement yet.

How does array work with MySQL in php

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • How does array work with MySQL in php

    How to use arrays in php?
    I want to know how can the data add to a table, can an arrays pass data in different rows or columns only?

    If I have a table with:
    id | Color | fruit

    Like this:
    If I had an array:
    $fruit = array("1", "Red", "Strawberry");

  • #2
    hi, Moriana,

    Yes you can do something with your example like this

    PHP Code
    Code:
    foreach($fruit as $val) {
       echo "<td>".$val."<\td>";
    }
    that will output each column of the table. You must to build the table around it, this is just a snippet for the columns.

    This is if you had an array of array holding all the data for fruit. You will then be able to draw the rows and columns e.g.

    PHP Code
    Code:
    $fruit = array(
             array("1", "Red", "Strawberry"),
             array("2", "Red", "Apple"),
             array("3", "Yellow", "Banana"),
    );
    
    foreach($fruit as $afruit) {
       echo "<tr>";
       echo "<td>".$afruit[0]."<\td>";
       echo "<td>".$afruit[1]."<\td>";
       echo "<td>".$afruit[2]."<\td>";
       echo "</tr>";
    }

    Comment


    • #3
      Here is a little example, hope this helps

      Code:
      <?php
      $db_host = "localhost";
      $db_user = "root";
      $db_pass = "";
      $db_name = "test";
      $mysqli = mysqli_connect($db_host,$db_user,$db_pass,$db_name) or die("Error " . mysqli_error($link)); 
      
      $data = file("data.csv"); // get data from csv file into array
      
      $query = ""; // build query string
      
      foreach($data as $row) {
      
      	list($id,$color,$fruit) = explode(",",$row); // split each column from csv
      
      	print "$id $color $fruit<br>";
      
      	$query .= "INSERT INTO fruits VALUES('$id','$color','$fruit');"; // build query
      
      }
      
      $mysqli->multi_query($query); // execute queries 
      
      ?>

      Comment

      Working...
      X