47: Inserting database results into array in PHP – PHP tutorial



Inserting database results into array in PHP – Learn PHP backend programming. Today we will learn how to insert data from a database table into an array.

➤ GET ACCESS TO MY LESSON MATERIAL HERE!

First of all, thank you for all the support you have given me!

I am really glad to have such an awesome community on my channel. It motivates me to continue creating and uploading content! So thank you!

I am now using Patreon to share improved and updated lesson material, and for a small fee you can access all the material. I have worked hard, and done my best to help you understand what I teach.

I hope you will find it helpful 🙂

Material for this lesson:

Nguồn: https://svdpch.org/

Xem thêm bài viết khác: https://svdpch.org/cong-nghe/

48 thoughts on “47: Inserting database results into array in PHP – PHP tutorial”

  1. thank you so much!! you help me for my database project for the university (hello from Athens)

    Reply
  2. For printing all the rows you can try that:
    for($i = 0; $i < (mysqli_num_rows($result)); $i++){

    foreach($data[$i] as $item){

    echo $item." ";

    }

    echo "<br>";

    }

    Reply
  3. Hello mmtuts how do i compare database data with form input data? They are both sentences, how do i compare each of the words of those data one by one?

    Reply
  4. Hi Daniel, thank you for this tutorial, it's very helpful. but where are the 36-44 episodes ??!! there're missing. please advise. thank you

    Reply
  5. hello sir how are you doing, thank you for you tutorial, but i have one issue that i want you to help me because am working on my theist and i have error to submit my student attendance using mysqli array here are the code below
    (
    =========== this part is the form side ========
    <form action="multiple-save.php" method="post">

    <div class="modal fade" id="modal-default" style="display: none;">

    <div class="modal-dialog">

    <div class="modal-content">

    <div class="modal-header">

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">

    <span aria-hidden="true">×</span></button>

    <h4 class="modal-title">Mark Class Attendance</h4>

    </div>

    <?php

    $s = "SELECT * FROM grade WHERE grade_id = (SELECT teacher_grade_id FROM staff

    WHERE id = '".$_SESSION["TID"]."')";

    $res = $db->query($s);

    if ($res->num_rows > 0);

    // $i = 0;

    ?>

    <!– ++$i; –>

    <div class="modal-body">

    <?php

    while ($row = $res->fetch_assoc()) {

    ?>

    <?php

    $numbers = $_POST['number'];

    for ($i=0; $i <=$numbers ; $i++) {

    # code…

    ?>

    <div class="box-body">

    <div class="form-group">

    <div class="row">

    <label class="col-md-4 text-right">Grade <span

    class="text-danger">*</span></label>

    <div class="col-md-8">

    <?php

    echo '<label>'.$row["grade_name"].'</label>';

    ?>

    </div>

    </div>

    </div>

    <input type="hidden" name="numbers" value="<?php echo $numbers;?>">

    <div class="form-group">

    <div class="row">

    <label class="col-md-4 text-right">Attendance Date <span

    class="text-danger">*</span></label>

    <div class="col-md-8">

    <input type="date" name="attendance_date" id="attendance_date"

    class="form-control" placeholder="yyyy-mm-dd" />

    <span id="error_attendance_date" class="text-danger"></span>

    </div>

    </div>

    </div>

    </div>

    <div class="form-group" id="student_details">

    <div class="table-responsive">

    <table class="table table-striped table-bordered">

    <thead>

    <tr>

    <th>Roll No.</th>

    <th>Student Name</th>

    <th>Present</th>

    <th>Absent</th>

    </tr>

    </thead>

    <?php

    $sl = "

    SELECT * FROM student s inner join grade g on s.student_grade_id = g.grade_id

    WHERE student_grade_id = '".$row['grade_id']."'

    ";

    $r = $db->query($sl);

    if ($r->num_rows > 0) {

    while ($ro = $r->fetch_assoc()) {

    // }

    // }

    ?>

    <tr>

    <td><?php echo $ro["RNO"]; ?></td>

    <td>

    <?php echo $ro["NAME"]; ?>

    <input type="hidden" name="student_id[]"

    value="<?php echo $ro["ID"]; ?>" />

    <input type="hidden" name="teacher_id[]"

    value="<?php echo $_SESSION["TID"]; ?>" />

    </td>

    <td align="center">

    <input type="radio"

    name="attendance_status<?php echo $ro["ID"]; ?>" checked

    value="Present" />

    </td>

    <td align="center">

    <input type="radio"

    name="attendance_status<?php echo $ro["ID"]; ?>" checked

    value="Absent" />

    </td>

    </tr>

    <?php

    }

    ?>

    </table>

    </div>

    </div>

    <?php

    }

    ?>

    <?php

    }

    ?>

    <?php }?>

    </div>

    <div class="modal-footer">

    <button type="button" class="btn btn-default pull-left"

    data-dismiss="modal">Close</button>

    <button type="submit" name="submit" class="btn btn-success"><span

    class="glyphicon glyphicon-floppy-save"> Mark-Attendance</button>

    </div>

    </div>

    <!– /.modal-content –>

    </div>

    <!– /.modal-dialog –>

    </div>

    </div>

    </form>

    <!– /.box –>

    ======= and this side is the action side ======

    <?php

    include '../database.php';

    $s = "insert into tbl_attendance(student_id,attendance_status,attendance_date,teacher_id) values";

    for($i=0;$i<$_POST['numbers'];$i++)

    {

    $s .="('".$_POST['student_id'][$i]."','".$_POST['attendance_status'][$i]."','".$_POST['attendance_date'][$i]."','{".$_POST['teacher_id'][$i]."'),";

    }

    $s = "insert into multiple(name,lastname,country) values";

    for($i=0;$i<$_POST['numbers'];$i++)

    {

    $s .="('".$_POST['name'][$i]."','".$_POST['lastname'][$i]."','".$_POST['country'][$i]."'),";

    }

    for($count = 0; $count < $_POST[$student_id]; $count++)

    {

    $data = array(

    ':student_id' => $student_id[$count],

    ':attendance_status' => $_POST["attendance_status".$student_id[$count].""],

    ':attendance_date' => $attendance_date,

    ':teacher_id' => $_SESSION["TID"]

    );

    $query = "

    INSERT INTO tbl_attendance

    (student_id, attendance_status, attendance_date, teacher_id)

    VALUES (:student_id, :attendance_status, :attendance_date, :teacher_id)

    ";

    $query = rtrim($query,",");

    if(!$db->query($query))

    echo ' Data failed: '.mysqli_connect_error();

    // echo mysqli_error();

    else

    echo "Records Saved <br />";

    }

    ?>

    Reply
  6. This tutorial playlist has been amazing so far! I'm super new to php coding and I make sure to follow your tutorials asclosely as possible and it has gone well 🙂
    I did the same with the code in this video and created the database and table like yours and keep getting this error message:

    Warning: mysqli_connect(): (HY000/1045): Access denied for user ''@'localhost' (using password: NO) in C:xampphtdocstrialsandtribsARRAYSdbh.php on line 8

    connection failed: Access denied for user ''@'localhost' (using password: NO)

    I don't know how to fix this or where to start. Please help weeps like child

    Reply
  7. Hello nice tuts. I HAVE A QUESTION. Related to array, can you explain why we put html input checkbox name= "checkbox [ ] " . How those brackets as key can turn into value in an array? I dont get it. Thanks pal you awesome.

    Reply
  8. Hey,

    I learn a lot from this channel. I'm just a beginner in php and mysqli.

    Yet I already have a compexe question. I am looking for a code / instruction how to make a matrix (multiple dimensional array ????? (I don't know)).

    What I have is a three table database

    table 'user' a table 'role' and a connection table 'person2role'.

    Now I am looking at how I can display the roles horizontally and the users vertically.

    where the tables intersect should be a +.

    for example:

    role1 role2 role3

    user1 x

    user2 x x

    user3 x

    Reply
  9. why do you name the part which is connecting to the database and executing a piece of sql code $result ? wouldnt $execute or $sqlCode be better?

    Reply
  10. Thank you dude, im currently at my exams and you really helped me out. You dont know how much you helped people around the word with this video <3

    Reply
  11. Greetings Sir!
    From your example how could i use to save only these ids,texts in another table?
    Im using php PDOs?
    Waiting to hear from you!

    Reply
  12. Hi, is it possible that if I only want selected columns in array (not all at once)?
    Fx. I have 7 columns in my table in database. I only want to insert results from column nr. 6, 1 and 2, and I want to insert these results in this order (row[6], row[1], row[2]).
    What should I do so??

    Reply
  13. Would it not be better if you use references like : 1D Arrays -> | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
    2D Arrays -> | 00 | 01 | 02 | 03 |
    | 10 | 11 | 12 | 13 |
    | 20 | 21 | 22 | 23 |
    | 30 | 31 | 32 | 33 |

    3D Arrays -> as cubes
    instead of just saying multi-dimensional array

    Also you should explain how the mysqli_query() function returns the result like

    id text
    ————————-
    0 | 1 | Hi | -> Array 1
    1 | 2 | there | -> Array 2
    2 | 3 | friend | -> Array 3

    ResultArray = ( Array1, Array2, Array3 ) ;

    Reply
  14. After watching this, I felt inspired to play around with multi-dimensional arrays as a fun challenge. I was adding arrays inside arrays containing array, next thing I know, I'm stuck inside the 5th dimension, flying through a black hole and shaking my astronaut hand with Matthew McConaughey and wondering if love is the only thing in the universe capable of transcending time and space.

    Reply
  15. what about if I have some empty row inside column result? how can I escape that empty row? please help….

    Reply
  16. Is it possible to get each value inside the text column separately(not all at once)? And also, without referencing the id for each text. Can someone answer this please?

    Reply
  17. Hello Daniel,

    Just a heads up when you show us a dump from a print_r then instead of just doing that, so it looks so messy, then arooung the print_r(); you can echo '<pre>' and close it after the print_r functions like echo '</pre>' and you will get a much more clean look..

    Reply
  18. Does anyone know what the best way to pass a multi-dimensional array to a new page is. Is it best to use SESSIONS or to serialise the variable and use POST and then unserialise on the other page? Or is there some other method that would be more appropriate?

    Reply
  19. can you help me , i checked all five times and everysingle time it echo me an error that say`s
    Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:xampphtdocsphplessonsarraysindex.php on line 16.

    my code :

    <?php
    include_once "dbh.php"
    ?>

    <!DOCTYPE html>
    <html>
    <head>
    <title></title>
    </head>
    <body>
    <?php

    $sql = "SELECT * FROM data";
    $result =mysqli_query($conn, $sql);
    $datas = array();
    if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
    $datas[] = $row;
    }
    }

    ?>
    </body>
    </html>

    do you know the problem ?

    Reply

Leave a Comment