MY SQL AND A ND P H P DA TA B A SE CON NE C TI VI TY How to show data from sql tables? connect_error) { die("Connection die("Connection failed: " . $conn->connect_error); $conn->connect_error); } $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql); $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "
id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"] . "
"; } } else { echo "0 results"; } $conn->close(); ?>
How to Show Data of sql in tabular form connect_error) { die("Connection die("Connection failed: " . $conn->connect_error); } $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows > 0) { echo "
ID | Name |
---|
ID | Name |
"; >"; // output data of each row while($row = $result->fetch_assoc()) { echo "" . $row["id"]. " | " . $row["firstname"]. " " . $row["lastname"]. " |
"; } echo "
"; } else { echo "0 results"; } $conn->close(); ?>
Program to use SQL Procedure to show database data 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
"; } } else { echo "0 results"; } mysqli_close($conn); ?>
Using PDO Technique for database connectivity "; echo "
Id | Firstname | Lastname |
---|
"; class TableRows extends RecursiveIteratorIterator { function __construct($it) { parent::__construct($it, self::LEAVES_ONLY); } function current() { return "
" . parent::current(). " | "; } function beginChildren() { echo "
"; } function endChildren() { echo "
" . "\n"; } } $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests"); $stmt->execute(); // set the resulting array to associative $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt>fetchAll())) as$k=>$v) { echo $v; } } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } $conn = null; echo ""; ?> Mysql Affected Rows function Details Example
Definition and Usage
Print out affected rows from different queries:
mysqli_autocommit() Function
The mysqli_affected_rows() function returns the number of affected rows in the previous SELECT, INSERT, UPDATE, REPLACE, or DELETE query. Syntax mysqli_affected_rows(connection);
Parameter
Description
connection
Required. Specifies the MySQL connection to use
Example
// Perform queries and print out affected rows mysqli_query($con,"SELECT * FROM Persons"); echo "Affected rows: " . mysqli_affected_rows($con);
Turn off auto-committing, make some queries, then commit the queries:
mysqli_query($con,"DELETE FROM Persons WHERE Age>32"); echo "Affected rows: " . mysqli_affected_rows($con);
// Set autocommit to off mysqli_autocommit($con,FALSE);
mysqli_close($con); ?>
// Insert some values mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Peter','Griffin',35)"); mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)"); // Commit transaction mysqli_commit($con);
// Close connection mysqli_close($con); ?> Definition and Usage The mysqli_autocommit() function turns on or off auto-committing database modifications. Tip: Also look at the mysqli_commit() f unction, which commits the current transaction for the specified database connection, and the mysqli_rollback() function, which rolls back the current transaction.
Syntax mysqli_autocommit(connection,mode); Parameter
Description
connection
Required. Specifies the MySQL connection to use
mode
Required. FALSE turns auto-commit off. TRUE turns auto-commit on (and commits any waiting queries)
mysqli_change_user() Function Example Change the user of the specified database connection:
// Reset all and select a new database mysqli_change_user($con, "my_user", "my_password", "my_test"); mysqli_close($con); ?> Definition and Usage The mysqli_change_user() function changes the user of the specified database connection, and sets the current database. Syntax mysqli_change_user(connection,username,password,dbname); Parameter
Description
connection
Required. Specifies the MySQL connection to use
username
Required. Specifies the MySQL username
password
Required. Specifies the MySQL password
dbname
Required. Specifies the database to change to
mysqli_close() Function Example Close a previously opened database connection:
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } ?> Definition and Usage The mysqli_connect() function opens a new connection to the MySQL server.
mysqli_close($con); ?>
Syntax mysqli_connect(host,username,password,dbname,port,socket );
Definition and Usage The mysqli_close() function closes a previously opened database connection. Syntax mysqli_close(connection);
Parameter
Description
host
Optional. Specifies a host name or an IP address
username
Optional. Specifies the MySQL username
Parameter
Description
password
Optional. Specifies the MySQL password
connection
Required. Specifies the MySQL connection to close
dbname
Optional. Specifies the default database to be used
port
Optional. Specifies the port number to attempt to connect to the MySQL server
socket
Optional. Specifies the socket or named pipe to be used
mysqli_connect() Function Example Open a new connection to the MySQL server:
mysqli_data_seek() Function Example Seek to row number 15 in the result-set:
result
Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
offset
Required. Specifies the field offset. Must be between 0 and the total number of rows - 1
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; if ($result=mysqli_query($con,$sql)) { // Seek to row number 15 mysqli_data_seek($result,14); // Fetch row $row=mysqli_fetch_row($result); printf ("Lastname: %s Age: %s\n", $row[0], $row[1]); // Free result set mysqli_free_result($result); } mysqli_close($con); ?> Definition and Usage The mysqli_data_seek() function adjusts the result pointer to an arbitrary row in the result-set. Syntax mysqli_data_seek(result,offset );
mysqli_fetch_all() Function Example Fetch all rows and return the result-set as an associative array: Definition and Usage
Parameter
Description
The mysqli_fetch_all() function fetches all result rows and returns the result-set as an associative array, a numeric array, or both.
{ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
Note: This function is available only with MySQL Native Driver.
Syntax mysqli_fetch_all(result,resulttype);
Parameter
Description
result
Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
resulttype
Optional. Specifies what type of array that should be produced. Can be one of the following values:
MYSQLI_ASSOC MYSQLI_NUM MYSQLI_BOTH
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; $result=mysqli_query($con,$sql); // Numeric array $row=mysqli_fetch_array($result,MYSQLI_NUM); printf ("%s (%s)\n",$row[0],$row[1]); // Associative array $row=mysqli_fetch_array($result,MYSQLI_ASSOC); printf ("%s (%s)\n",$row["Lastname"],$row["Age"]); // Free result set mysqli_free_result($result); mysqli_close($con); ?> Definition and Usage The mysqli_fetch_array() function fetches a result row as an associative array, a numeric array, or both. Note: Fieldnames returned from this function are case-sensitive.
mysqli_fetch_array() Function Example Fetch a result row as a numeric arr ay and as an associative array:
Syntax mysqli_fetch_array(result,resulttype);
Parameter
Description
result
Required. Specifies a result set identifier
returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
mysqli_close($con); ?> Definition and Usage
resulttype
Optional. Specifies what type of array that should be produced. Can be one of the following values:
The mysqli_fetch_assoc() function fetches a result r ow as an associative array. Note: Fieldnames returned from this function are case-sensitive.
MYSQLI_ASSOC MYSQLI_NUM MYSQLI_BOTH
mysqli_fetch_assoc() Function
Syntax mysqli_fetch_assoc(result );
Parameter
Description
result
Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
Example Fetch a result row as an associative array:
mysqli_fetch_field_direct() Function Example Return meta-data for a single field (column) in the result set, then print the field's name, table, and max length:
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; if ($result=mysqli_query($con,$sql)) { // Get field information for "Age" $fieldinfo=mysqli_fetch_field_direct($result,1); printf("Name: %s\n",$fieldinfo->name); printf("Table: %s\n",$fieldinfo->table); printf("max. Len: %d\n",$fieldinfo->max_length); // Free result set mysqli_free_result($result); } mysqli_close($con); ?>
mysqli_fetch_field() Function Example Return the next field (column) in the result set, then print each field's name, table, and max length:
Definition and Usage The mysqli_fetch_field_direct() function returns meta-data for a single field (column) in the result set, as an object. Syntax mysqli_fetch_field_direct(result,fieldnr );
Parameter
Description
result
Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
fieldnr
be an integer between 0 and number of fields -1
Required. Specifies the field number. Must
if ($result=mysqli_query($con,$sql)) { // Get field information for all fields while ($fieldinfo=mysqli_fetch_field($result)) { printf("Name: %s\n",$fieldinfo->name); printf("Table: %s\n",$fieldinfo->table); printf("max. Len: %d\n",$fieldinfo->max_length); } // Free result set mysqli_free_result($result); } mysqli_close($con); ?> Definition and Usage
The mysqli_fetch_field() function returns the next field ( column) in the result set, as an object.
foreach ($fieldinfo as $val) { printf("Name: %s\n",$val->name); printf("Table: %s\n",$val->table); printf("max. Len: %d\n",$val->max_length); } // Free result set mysqli_free_result($result);
Syntax mysqli_fetch_field(result );
Parameter
Description
result
Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
}
mysqli_fetch_fields() Function
Example Return an array of objects that represent the fields (columns) in a result set, then print each field's name, table, and max length:
mysqli_close($con); ?> Definition and Usage The mysqli_fetch_fields() function returns an array of objects that represent the fields (columns) in a result set. Syntax mysqli_fetch_fields(result );
Parameter
Description
result
Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
mysqli_fetch_row() Function $sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; if ($result=mysqli_query($con,$sql)) { // Get field information for all fields $fieldinfo=mysqli_fetch_fields($result);
Example Fetch rows from a result-set:
// Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
mysqli_query(), mysqli_store_result() or mysqli_use_result() mysqli_field_count() Function
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
Example
if ($result=mysqli_query($con,$sql)) { // Fetch one and one row while ($row=mysqli_fetch_row($result)) { printf ("%s (%s)\n",$row[0],$row[1]); } // Free result set mysqli_free_result($result); }
Assume we have a "Friends" table that has 3 fields and 20 rows. Return the number of columns for the most recent query:
mysqli_close($con); ?> Definition and Usage The mysqli_fetch_row() function fetches one row from a result-set and returns it as an enumerated array. Syntax mysqli_fetch_row(result );
Parameter
Description
result
Required. Specifies a result set identifier returned by
mysqli_close($con); ?> Definition and Usage The mysqli_field_count() function returns the number of columns for the most recent query.
Syntax mysqli_field_count(connection); mysqli_field_seek() Function Example
Set the field cursor to the first field ( column) in the result set, then get the field info with mysqli_fetch_field() and print the field's name, table, and max length:
Parameter
Description
result
Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
fieldnr
if ($result=mysqli_query($con,$sql)) { // Get field info for 1st column ("Lastname") mysqli_field_seek($result,0); $fieldinfo=mysqli_fetch_field($result);
Required. Specifies the field number. Must be an integer between 0 and number of fields -1
Example
printf("Name: %s\n",$fieldinfo->name); printf("Table: %s\n",$fieldinfo->table); printf("max. Len: %d\n",$fieldinfo->max_length); // Free result set mysqli_free_result($result); }
Fetch rows from a result-set, then free the memory associated with the result:
mysqli_close($con); ?>
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
Definition and Usage
if ($result=mysqli_query($con,$sql)) { // Fetch one and one row while ($row=mysqli_fetch_row($result)) { printf ("%s (%s)\n",$row[0],$row[1]); }
The mysqli_field_seek() function sets the field cursor to the given field offset. Syntax mysqli_field_seek(result,fieldnr );
// Free result set mysqli_free_result($result); } mysqli_close($con); ?> Definition and Usage The mysqli_free_result() function frees the memory associated with the result. Syntax mysqli_free_result(result );
Parameter
Description
result
Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
mysqli_multi_query() Function
$sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers"; // Execute multi query if (mysqli_multi_query($con,$sql)) { do { // Store first result set if ($result=mysqli_store_result($con)) { // Fetch one and one row while ($row=mysqli_fetch_row($result)) { printf("%s\n",$row[0]); } // Free result set mysqli_free_result($result); } } while (mysqli_next_result($con)); } mysqli_close($con); ?>
Example
Definition and Usage
Perform multiple queries against the database:
The mysqli_multi_query() function performs one or more queries against the database. The queries are separated with a semicolon. Syntax mysqli_multi_query(connection,query);
Parameter
Description
connection
query
} mysqli_free_result($con); }
Required. Specifies the MySQL connection to use
Required. Specifies one or more queries, seperated with semicolon
} while (mysqli_next_result($con)); }
mysqli_next_result() Function
mysqli_close($con); ?>
Example
Definition and Usage
Perform multiple queries against the database. Use mysqli_next_result() function to prepare the next result set:
The mysqli_next_result() function prepares the next result set from mysqli_multi_query().
$sql = "SELECT Lastname FROM Persons ORDER BY LastName;"; $sql .= "SELECT Country FROM Customers"; // Execute multi query if (mysqli_multi_query($con,$sql)) { do { // Store first result set if ($result=mysqli_store_result($con)) { while ($row=mysqli_fetch_row($result)) { printf("%s\n",$row[0]);
Syntax mysqli_next_result(connection);
Parameter
Description
connection
Required. Specifies the MySQL connection to use
mysqli_num_fields() Function
Example Return the number of fields (columns) in a r esult set:
echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; if ($result=mysqli_query($con,$sql)) { // Return the number of fields in result set $fieldcount=mysqli_num_fields($result); printf("Result set has %d fields.\n",$fieldcount); // Free result set mysqli_free_result($result); } mysqli_close($con); ?> Definition and Usage The mysqli_num_fields() function returns the number of fields (columns) in a result set. Syntax mysqli_num_fields(result );
Example Return the number of rows in a re sult set:
Parameter
Description
result
Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
Definition and Usage The mysqli_num_rows() function returns the number of rows in a result set. Syntax mysqli_num_rows(result );
mysqli_num_rows() Function Parameter
Description
result
Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
Parameter
Description
connection
Required. Specifies the MySQL connection to use
query
Required. Specifies the query string
mysqli_query() Function
Example Perform queries against the database: Definition and Usage
Optional. A constant. Either: resultmode
MYSQLI_USE_RESULT (Use this if we have to retrieve large amount of data) MYSQLI_STORE_RESULT (This is default)
mysqli_real_connect() Function
Example Open a new connection to the MySQL server:
The mysqli_query() function performs a query against the database. Syntax mysqli_query(connection,query,resultmode);
if (!mysqli_real_connect($con,"localhost","my_user","my_password","my _db")) {
die("Connect Error: " . mysqli_connect_error()); } mysqli_close($con); ?>
password
Optional. Specifies the MySQL password
dbname
Optional. Specifies the default database to be used
port
Optional. Specifies the port number to attempt to connect to the MySQL server
socket
Optional. Specifies the socket or named pipe to be used
flag
Optional. Specifies different connection options. Possible values:
Definition and Usage The mysqli_real_connect() function opens a new connection to the MySQL server. The mysqli_real_connect() function differs from mysqli_connect() in the following ways:
mysqli_real_connect() requires a valid object created by mysqli_init() mysqli_real_connect() can be used with mysqli_options() to set different options for the connection mysqli_real_connect() has a flag parameter
Syntax mysqli_real_connect(connection,host,username,password,dbname,port,s ocket,flag );
Parameter
Description
connection
Required. Specifies the MySQL connection to use
host
Optional. Specifies a host name or an IP address
username
Optional. Specifies the MySQL username
MYSQLI_CLIENT_COMPRESS - Use compression protocol MYSQLI_CLIENT_FOUND_ROWS Return number of matched rows (not affected rows) MYSQLI_CLIENT_IGNORE_SPACE Allow spaces after function names. Make function names reserved words MYSQLI_CLIENT_INTERACTIVE Allow interactive_timeout seconds of inactivity before closing connection MYSQLI_CLIENT_SSL - Use SSL encryption
mysqli_real_escape_string() Function
Example Escape special characters in a string: Definition and Usage The mysqli_real_escape_string() function escapes special characters in a string for use in an SQL statement. Syntax mysqli_real_escape_string(connection,escapestring );
Parameter
Description
connection
Required. Specifies the MySQL connection to use
escapestring
Required. The string to be escaped. Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.