Bagaimana Anda mengambil data dari database di php menggunakan mysqli?

Di kumpulan artikel kami sebelumnya, kami telah membuat situs web 2 halaman sederhana yang memungkinkan pengguna mengirimkan komentar tentang halaman yang mereka lihat. Pada artikel ini, kami akan menunjukkan cara menggunakan PHP untuk Menghubungkan dan Mengambil Data dari MySQL

Langkah 1. Buat SQL Query kami untuk mengambil semua komentar

Untuk menampilkan komentar pada halaman, pertama-tama kita perlu mengetahui komentar apa yang akan ditampilkan. Saat kami menyiapkan situs kami, kami membuat dua halaman, dan setiap halaman diberi nomor id unik. Nomor ID ini akan digunakan untuk mengumpulkan komentar untuk halaman tertentu. Misalnya, saat pengguna berada di halaman 1, kami akan memilih semua komentar di database yang ditetapkan ke halaman “1”

Jika Anda tidak terbiasa dengan SQL, Anda dapat menggunakan phpMyAdmin untuk membantu menulis perintah SQL Anda. Untuk melakukan ini

  1. Masuk ke cPanel dan klik ikon phpMyAdmin
  2. Di menu sebelah kiri, pertama klik nama database Anda, lalu klik tabel untuk dikerjakan. Jika Anda mengikuti contoh kami, pertama-tama kami akan mengklik "_mysite" dan kemudian "comments"
  3. Klik "Cari" di menu atas
  4. Masukkan 1 untuk “Value” dari “articleid” dan kemudian klik “Go”
    Bagaimana Anda mengambil data dari database di php menggunakan mysqli?

     

  5. Setelah menjalankan pencarian, phpMyAdmin akan menampilkan semua komentar yang termasuk dalam artikel 1, serta sintaks SQL yang dapat Anda gunakan untuk memilih komentar tersebut. Kode yang diberikan adalah. SELECT * FROM `comments` WHERE `articleid` =1 LIMIT 0 , 30

    Bagaimana Anda mengambil data dari database di php menggunakan mysqli?

     

     

Langkah 2. Menyiapkan kode PHP kami untuk PILIH komentar kami

Perhatikan bahwa mysqli_fetch_array tidak digunakan lagi dalam versi PHP di bawah 7. 0. Pada 7. 0, kode telah dihapus dan diganti dengan mysqli_fetch-array

Sekarang setelah kita memiliki contoh kueri SQL, kita dapat menggunakannya untuk membuat kode php yang akan mencetak semua komentar di halaman. Di bawah ini adalah contoh kode yang kami buat. Jika Anda tidak terbiasa dengan php, setiap baris yang diawali dengan // adalah komentar, dan komentar digunakan oleh pengembang untuk mendokumentasikan kode mereka. Dalam contoh kami, kami memiliki beberapa komentar untuk membantu menjelaskan apa yang dilakukan kode, tetapi perlu diingat bahwa sebagian besar skrip tidak memiliki banyak komentar.

<?

// At this point in the code, we want to show all of the comments
// submitted by users for this particular page. As the comments
// are stored in the database, we will begin by connecting to
// the database
 
// Below we are setting up our connection to the server. Because
// the database lives on the same physical server as our php code,
// we are connecting to "localhost". inmoti6_myuser and mypassword
// are the username and password we setup for our database when
// using the "MySQL Database Wizard" within cPanel

$con = mysql_connect("localhost","inmoti6_myuser","mypassword");
 
// The statement above has just tried to connect to the database.
// If the connection failed for any reason (such as wrong username
// and or password, we will print the error below and stop execution
// of the rest of this php script

if (!$con)
{
  die('Could not connect: ' . mysql_error());
}
 
// We now need to select the particular database that we are working with
// In this example, we setup (using the MySQL Database Wizard in cPanel) a
// database named inmoti6_mysite

mysql_select_db("inmoti6_mysite", $con);

// We now need to setup our SQL query to grab all comments from this page.
// The example SQL query we copied from phpMyAdmin is:
// SELECT * FROM `comments` WHERE `articleid` =1 LIMIT 0 , 30
// If we run this query, it will ALWAYS grab only the comments from our
// article with an id of 1. We therefore need to update the SQL query
// so that on article 2 is searches for the "2", on page is searches for
// "3", and so on.
// If you notice in the URL, the id of the article is set after id=
// For example, in the following URL:
// https://phpandmysql.inmotiontesting.com/page2.php?id=2
// .. the article id is 2. We can grab and store this number in a variable
// by using the following code:

$article_id = $_GET['id'];

// We also want to add a bit of security here. We assume that the $article_id
// is a number, but if someone changes the URL, as in this manner:
// https://phpandmysql.inmotiontesting.com/page2.php?id=malicious_code_goes_here
// .. then they will have the potential to run any code they want in your
// database. The following code will check to ensure that $article_id is a number.
// If it is not a number (IE someone is trying to hack your website), it will tell
// the script to stop executing the page

if( ! is_numeric($article_id) )
  die('invalid article id');

// Now that we have our article id, we need to update our SQL query. This
// is what it looks like after we update the article number and assign the
// query to a variable named $query

$query = "SELECT * FROM `comments` WHERE `articleid` =$article_id LIMIT 0 , 30";

// Now that we have our Query, we will run the query against the database
// and actually grab all of our comments

$comments = mysql_query($query);

// Before we start writing all of the comments to the screen, let's first
// print a message to the screen telling our users we're going to start
// printing comments to the page.

echo "<h1>User Comments</h1>";

// We are now ready to print our comments! Below we will loop through our
// comments and print them one by one.

// The while statement will begin the "looping"

/*NOTE that in PHP 7.0, the mysql_fetch_array has been removed -it was previously deprecated 
in earlier versions of PHP.  You find the cod documentation here:  
https://php.net/manual/en/function.mysql-fetch-array.php */

while($row = mysql_fetch_array($comments, MYSQL_ASSOC))
{

  // As we loop through each comment, the specific comment we're working
  // with right now is stored in the $row variable.

  // for example, to print the commenter's name, we would use:
  // $row['name']
  
  // if we want to print the user's comment, we would use:
  // $row['comment']
  
  // As this is a beginner tutorial, to make our code easier to read
  // we will take the values above (from our array) and put them into
  // individual variables

  $name = $row['name'];
  $email = $row['email'];
  $website = $row['website'];
  $comment = $row['comment'];
  $timestamp = $row['timestamp'];

  $name = htmlspecialchars($row['name'],ENT_QUOTES);
  $email = htmlspecialchars($row['email'],ENT_QUOTES);
  $website = htmlspecialchars($row['website'],ENT_QUOTES);
  $comment = htmlspecialchars($row['comment'],ENT_QUOTES);
  
  // We will now print the comment to the screen
  
  echo "  <div style='margin:30px 0px;'>
      Name: $name<br />
      Email: $email<br />
      Website: $website<br />
      Comment: $comment<br />
      Timestamp: $timestamp
    </div>
  ";
}

// At this point, we've added the user's comment to the database, and we can
// now close our connection to the database:
mysql_close($con);

?>

Seperti yang dinyatakan sebelumnya, kami sengaja menyertakan banyak komentar untuk membantu menjelaskan apa yang dilakukan kode tersebut. Meskipun kode contoh di atas terlihat seperti banyak pekerjaan, jika kita menghapus semua komentar, kode tersebut akan terlihat lebih mirip

<?

$con = mysql_connect("localhost","inmoti6_myuser","mypassword");
 
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}
 
mysql_select_db("inmoti6_mysite", $con);

$article_id = $_GET['id'];

if( ! is_numeric($article_id) )
  die('invalid article id');

$query = "SELECT * FROM `comments` WHERE `articleid` =$article_id LIMIT 0 , 30";

$comments = mysql_query($query);

echo "<h1>User Comments</h1>";

// Please remember that  mysql_fetch_array has been deprecated in earlier
// versions of PHP.  As of PHP 7.0, it has been replaced with mysqli_fetch_array.  

while($row = mysql_fetch_array($comments, MYSQL_ASSOC))
{
  $name = $row['name'];
  $email = $row['email'];
  $website = $row['website'];
  $comment = $row['comment'];
  $timestamp = $row['timestamp'];
  
  // Be sure to take security precautions! Even though we asked the user
  // for their "name", they could have typed anything. A hacker could have
  // entered the following (or some variation) as their name:
  //
  // <script type="text/javascript">window.location = "https://SomeBadWebsite.com";</script>
  //
  // If instead of printing their name, "John Smith", we would be printing
  // javascript code that redirects users to a malicious website! To prevent
  // this from happening, we can use the <a href="https://php.net/htmlspecialchars" target="_blank">htmlspecialchars function</a> to convert
  // special characters to their HTML entities. In the above example, it would
  // instead print:
  //
  // <span style="color:red;"><</span>script type=<span style="color:red;">"</span>text/javascript<span style="color:red;">"></span>window.location = <span style="color:red;">"</span>https://SomeBadWebsite.com<span style="color:red;">"</span>;<span style="color:red;"><</span>/script<span style="color:red;">></span>
  //
  // This certainly would look strange on the page, but it would not be harmful
  // to visitors
  
  $name = htmlspecialchars($row['name'],ENT_QUOTES);
  $email = htmlspecialchars($row['email'],ENT_QUOTES);
  $website = htmlspecialchars($row['website'],ENT_QUOTES);
  $comment = htmlspecialchars($row['comment'],ENT_QUOTES);
  
  echo "  <div style='margin:30px 0px;'>
      Name: $name<br />
      Email: $email<br />
      Website: $website<br />
      Comment: $comment<br />
      Timestamp: $timestamp
    </div>
  ";
}

mysql_close($con);

?>
_

Langkah 3. Menempatkan kode php kami ke halaman kami

Kami sekarang memiliki kode php kami yang akan menampilkan komentar ke layar. Pada artikel sebelumnya, kami menjelaskan cara menggunakan fungsi include php untuk menggunakan kembali kode, dan kami akan terus menggunakan metode ini untuk menggunakan kode php kami

Untuk memasukkan kode php kami

  1. Buat file bernama display_comments. php
  2. Rekatkan kode contoh di atas
  3. Perbarui kedua halaman1. php dan halaman2. php untuk memasukkan display_comments. php dengan menggunakan. <? include("display_comments.php"); ?>_

    menuju bagian bawah halaman di mana Anda ingin menampilkan komentar

Setelah melakukan langkah-langkah di atas, halaman kita1. file php sekarang terlihat seperti ini

<? include("manage_comments.php"); ?>

<h1>This is page1.php</h1>

<div><a href='page2.php?id=2'>Click here</a> to go to page2.php</div>

<div style='margin:20px; width:100px; height:100px; background:blue;'></div>

<? include("display_comments.php"); ?>

<? include("formcode.php"); ?>

Setelah menguji dua halaman kami, Anda dapat melihat bahwa setiap halaman hanya menampilkan komentar yang ditambahkan ke halaman tersebut

Bagaimana cara mendapatkan data dari database di PHP?

Ambil atau Ambil Data Dari Basis Data di PHP .
PILIH nama_kolom DARI nama_tabel
$query = mysql_query("pilih * dari namatabel", $koneksi);
$koneksi = mysql_connect("localhost", "root", "");
$db = mysql_select_db("perusahaan", $koneksi);
$query = mysql_query("pilih * dari karyawan", $koneksi);

Saat mengambil data dari database menggunakan fungsi Mysqli_fetch_row () apa yang dikembalikan ke fungsi pemanggil?

Fungsi fetch_row() / mysqli_fetch_row() mengambil satu baris dari kumpulan hasil dan mengembalikannya sebagai array yang disebutkan .

Bagaimana cara mengambil catatan data tunggal dari database menggunakan PHP MySQL?

Menampilkan catatan menggunakan fungsi MySQLI

Bagaimana cara menyimpan dan mengambil data dari database di PHP?

Menyimpan Data di Database . Untuk mengambil data file yang akan digunakan dalam kueri, Anda harus memanggil fungsi file_get_contents() PHP, yang membaca file menjadi string. $file_data = file_get_contents($file);All that's required by the PHP script is a standard INSERT query, using the binary data for the file column value. To grab the file data to be used in the query, you must call the PHP file_get_contents() function, which reads a file into a string: $file_data = file_get_contents($file);