MySQL::BuildSQLWhereClause PHP Method

BuildSQLWhereClause() public static method

If a key is specified, the key is used at the field name and the value as a comparison. If a key is not used, the value is used as the clause.
public static BuildSQLWhereClause ( array $whereArray ) : string
$whereArray array An associative array containing the column names as keys and values as data. The values must be SQL ready (i.e. quotes around strings, formatted dates, ect)
return string Returns a string containing the SQL WHERE clause
    public static function BuildSQLWhereClause($whereArray)
    {
        $where = "";
        foreach ($whereArray as $key => $value) {
            if (strlen($where) == 0) {
                if (is_null($value)) {
                    $where = " WHERE `" . $key . "` IS NULL";
                } else {
                    if (is_string($key)) {
                        $where = " WHERE `" . $key . "` = " . $value;
                    } else {
                        $where = " WHERE " . $value;
                    }
                }
            } else {
                if (is_null($value)) {
                    $where = " AND `" . $key . "` IS NULL";
                } else {
                    if (is_string($key)) {
                        $where .= " AND `" . $key . "` = " . $value;
                    } else {
                        $where .= " AND " . $value;
                    }
                }
            }
        }
        return $where;
    }

Usage Example

Beispiel #1
0
echo "Are we connected? ";
var_dump($db->IsConnected());
echo "\n<br />\n";
// --------------------------------------------------------------------------
// Now we can generate SQL statements from arrays!
// Let's create an array for the examples
// $arrayVariable["column name"] = formatted SQL value
$values["Name"] = MySQL::SQLValue("Violet");
$values["Age"] = MySQL::SQLValue(777, MySQL::SQLVALUE_NUMBER);
// Echo out some SQL statements
echo "<pre>" . "\n";
echo MySQL::BuildSQLDelete("Test", $values) . "\n<br />\n";
echo MySQL::BuildSQLInsert("Test", $values) . "\n<br />\n";
echo MySQL::BuildSQLSelect("Test", $values) . "\n<br />\n";
echo MySQL::BuildSQLUpdate("Test", $values, $values) . "\n<br />\n";
echo MySQL::BuildSQLWhereClause($values) . "\n<br />\n";
echo "</pre>" . "\n";
// Or create more advanced SQL SELECT statements
$columns = array("Name", "Age");
$sort = "Name";
$limit = 10;
echo MySQL::BuildSQLSelect("Test", $values, $columns, $sort, true, $limit);
echo "\n<br />\n";
$columns = array("Color Name" => "Name", "Total Age" => "Age");
$sort = array("Age", "Name");
$limit = "10, 20";
echo MySQL::BuildSQLSelect("Test", $values, $columns, $sort, false, $limit);
echo "\n<br />\n";
// The following methods take the same parameters and automatically execute!
// $db->DeleteRows("Test", $values);
// $db->InsertRow("Test", $values);