PHP Function to Run MySql Queries Return Rows
PHP Function to Run MySql Queries Return Rows that uses PREPARE Statements to Prevent SQL Injection and htmlentities to Prevent XSS attacks
Home
Short:
/*----------------------------------------------------------------------------- function to simplify mysql commands PARAMETERS: [$dbConnection] the active database connection you have created [$selectWhat] which columns (the column names) ie "firstname, address" [$fromWhat] the name of the table to execute the sql command [$whereWhat] specific condition ie, "firstname = 'joe'" [$additional] optional additional parameters ie "ORDER BY RAND() LIMIT = 2" RETURNS: array [array of rows, row count] ---------------------------------------------------------------------------- */ function selectMySqlFrom($dbConnection, string $selectWhat, string $fromWhat, string $whereWhat, string $additional = "") { // Prepare the SQL statement with placeholders (security) $sql = "SELECT $selectWhat FROM $fromWhat WHERE $whereWhat $additional"; $stmt = mysqli_prepare($dbConnection, $sql); if ($stmt === false) { // enter any error handling code you wish return[false, 0]; } // Execute the prepared statement mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); $rowCount = mysqli_num_rows($result); // if rowCount == 0 if ($rowCount == 0) { return [false, $rowCount]; } $arrRows = []; if ($result) { while ($row = mysqli_fetch_assoc($result)) { // Process each row and clean with htmlentities $cleanRow = array_map("htmlentities", $row); // add this [$row] to [$arrRows[]] $arrRows[] = $cleanRow; } } // Free memory mysqli_free_result($result); mysqli_stmt_close($stmt); return [$arrRows, $rowCount]; }
source code home