Last active
January 16, 2018 03:03
-
-
Save Sarverott/20fc794b0db2b9c1e7479f0b42106049 to your computer and use it in GitHub Desktop.
simple function to connect with SQL server in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function connect_db($host=false, $user=false, $pass=false, $database=false, $query='SELECT 1', $throw_error=true){ | |
//defaults | |
if($host)$host='localhost'; | |
if($user)$user='root'; | |
if($pass)$pass=null; | |
$connection_object=null; | |
if($database){ | |
//connect to server, directly to database | |
$connection_object=new mysqli($hosr,$user,$password,$database); | |
}else{ | |
//connect to server | |
$connection_object=new mysqli($hosr,$user,$password); | |
} | |
if($conn->connect_error){ | |
//error on connect with database | |
if($throw_error){ | |
//if you want to hide error, give to 6'th argumnet false; DEFAULT - returning error string as below | |
echo "<b>#ERROR#</b> - It looks like a problem with connection...<b>check connection settings</b>(user:'$user', server:'$host', password:'$pass', database:'$database'): ".$connection_object->connect_error; | |
die(); | |
}else return false; //if error hidden, returning false | |
}else{ | |
//execute query, close connection and return data from query execution | |
$query_result=$connection_object->query($query); | |
$return_value=[]; | |
while($row_of_data=mysqli_fetch_assoc($query_result)){ | |
$return_value[]=$row_of_data; | |
} | |
$connection_object->close(); | |
return $return_value; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment