How can you prevent duplicate values from being stored in an array when fetching data from a MySQL query in PHP?
When fetching data from a MySQL query in PHP and storing it in an array, you can prevent duplicate values by using the PHP in_array() function to check if the value already exists in the array before adding it. This ensures that each value is unique within the array.
// Connect to MySQL database
$conn = new mysqli($servername, $username, $password, $dbname);
// Fetch data from MySQL query
$result = $conn->query("SELECT column_name FROM table_name");
// Initialize an empty array to store unique values
$dataArray = array();
// Loop through the query results and add unique values to the array
while($row = $result->fetch_assoc()) {
$value = $row['column_name'];
if (!in_array($value, $dataArray)) {
$dataArray[] = $value;
}
}
// Close database connection
$conn->close();
// Print the array of unique values
print_r($dataArray);
Keywords
Related Questions
- How can developers ensure that their PHP scripts remain secure and functional when facing limitations on server configurations?
- What are some resources or documentation that can help improve understanding of PHP database functions like mysqli_query?
- In what scenarios or contexts is it recommended to use PEAR:Mime class for processing special characters in PHP?