PHP :: MySQL Snippets

This snippet will connect to your MySQL database:

$mysqli = mysqli_connect('localhost', 'DATABASE_USER', 'DATABASE_PASS', 'DATABASE_NAME');

Check for connection errors:

if (mysqli_connect_errno()) {
	die('Failed to connect to MySQL: ' . mysqli_connect_error());

Select database table and display all the results:

$result = $mysqli->query('SELECT * FROM students');
while ($row = $result->fetch_assoc()) {
	echo $row['name'] . '<br>';

Checking the number of rows:


Insert a new record:

$mysqli->query('INSERT INTO students (name) VALUES ("David")');

Checking the number of affected rows:


Escape special characters in a string, this should be used if you do not prepare your statements:


Prepare statement, prevents SQL injection:

$name = 'Jonh doe';
$limit = 1;
$stmt = $mysqli->prepare('SELECT * FROM students WHERE name = ? LIMIT ?');
$stmt->bind_param('si', $name, $limit);
// etc...
$result = $stmt->get_result();

Close query and close database connection:


Leave a Reply

Your email address will not be published. Required fields are marked *