วันพฤหัสบดีที่ 29 ตุลาคม พ.ศ. 2558

PHP - จัดการ MySQL โดยใช้ mysqli prepare (select * from user)

จะมีการ bind param โดยใช้ค่าดังนี้
  • i   corresponding variable has type integer 
  • d  corresponding variable has type double 
  • s   corresponding variable has type string 
  • b  corresponding variable is a blob and will be sent in packets 
สำหรับ insert id ให้ใช้ $statement->insert_id ได้

select *

            $sql = "select * from user";
            $stmt = $conn->prepare($sql);
            if ($stmt->execute()) {
                $rows = array();
                $data = array();

                $fileds = $stmt->result_metadata()->fetch_fields();

                echo '<table><tr>';

                foreach ($fileds as $f) {
                    echo '<th>' . $f->name . '</th>';

                    $rows[] = &$data[$f->name]; // pass by reference
                }

                echo '</tr>';

                call_user_func_array(array($stmt, 'bind_result'), $rows);

                while ($stmt->fetch()) {
                    echo '<tr>';

                    foreach ($rows as $r)
                        echo '<td>' . $r . '</td>';
                    //หรือใช้
                    foreach ($data as $d)
                        echo '<td>' . $d . '</td>';
                    //หรือใช้
                    foreach ($fileds as $f)
                        echo '<td>' . $data[$f->name] . '</td>';

                    echo '</tr>';
                }
                echo '</table>';

                $stmt->free_result();
                $stmt->close();
            } else {
                echo $stmt->error;
            }

ไม่มีความคิดเห็น:

แสดงความคิดเห็น