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:

$result->num_rows;

Insert a new record:

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

Checking the number of affected rows:

$mysqli->affected_rows;

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

$mysqli->real_escape_string($user_input_text);

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);
$stmt->execute();
// etc...
$result = $stmt->get_result();

Close query and close database connection:

$stmt->close();
$mysqli->close();

Leave a Reply

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

*