Skip to content

Instantly share code, notes, and snippets.

@tournasdim
Created June 25, 2013 07:21
Show Gist options
  • Save tournasdim/5856604 to your computer and use it in GitHub Desktop.
Save tournasdim/5856604 to your computer and use it in GitHub Desktop.
Mysqli connection example (using procedural style)
<?php
// Create connection
$con = mysqli_connect("localhost", "username", "password", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Create table doesn't return a resultset */
if (mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n" );
}
/* Select queries return a resultset */
if ($result = mysqli_query($con , "SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
while ( $results = mysqli_fetch_row($qeury) )
{
// logic here
} // End of while loop
/* free result set */
mysqli_free_result($result);
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = mysqli_query($con , "SELECT * FROM City", MYSQLI_USE_RESULT)) {
/*
Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error
*/
if (!mysqli_query($con , "SET @a:='this will not work'")) {
printf("Error: %s\n", mysqli_error($con));
}
mysqli_free_result($result);
}
mysqli_close($con);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment