Last active
April 27, 2018 08:46
-
-
Save vaibhavhrt/500ab71d2c94b8ce0f4e6f2584eea755 to your computer and use it in GitHub Desktop.
php function to query and get one row from a mysql database
This file contains hidden or 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
define('DB_SERVER', 'localhost'); | |
define('DB_USERNAME', 'username'); | |
define('DB_PASSWORD', 'password'); | |
define('DB_NAME', 'database_name'); | |
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME); | |
// Check connection | |
if($con === false){ | |
die("ERROR: Could not connect. " . mysqli_connect_error()); | |
} | |
//function to get one row | |
function getRowFromId($uId, $c){ | |
$query = mysqli_query($c, "SELECT * FROM table where id=$uId"); //replace * will name of columns if you want specific columns only | |
$row = mysqli_fetch_row($query); | |
return $row; //returns an array | |
} | |
//call function | |
$name = getRowFromId($some_unique_id, $con); //don't forget to pass the MySQL link identifier, otherwise if won't work | |
//$some_unique_id = any column to uniquely identify each row, IMO use primary key | |
//function will return an array of size of number of columns in db | |
print_r($name); //to view the whole array | |
echo $name[0]; | |
echo $name[1]; //use index 0 to sizeof($name)-1 to access each value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment