Breaking News
Home / Web / PHP / PHP Snippets / How to connect and execute query against Mysql using Php?

How to connect and execute query against Mysql using Php?

PHP MYSQL Database ScriptA very basic and essential snippet for any one starting with php and mysql database i.e. to connect to a given database, execute a custom sql and retrieve the results. The snippet can be modified to execute more than one query or execute an update or insert command instead of the query. The following snippet show exactly how to do so..<!

<?php

/**
 * This snippet shows how to connect to the database,
 * execute a sql query and display the results
 */

// connect to the database server with username and password
$con = mysql_connect("localhost", "root", "");

// check if the connection succeeded else display error and exit
if (!$con) {
	die('Could not connect to database: ' . mysql_error());
}

// database name
$database = "mysql";

// select the database to use
mysql_select_db($database, $con);

// execute the sql query and get the result
$sql = "SELECT * FROM user";
$result = mysql_query($sql);

$rowno = 0;
// iterate through the result set and display fields
while ($row = mysql_fetch_array($result)) {

	$rowno++;
	// display the column values
	// columns names are case sensitive
	printf( $rowno . ") user: " . $row['User'] . " host: " . $row['Host'] . "n");
}

// finally close the connection
mysql_close($con);
?>

 [pb_builder]

Check Also

How to list files in a directory in PHP?

<?php if ($handle = opendir(‘/path/to/directory’)) {     echo "Directory handle: $handlen";     echo …

Leave a Reply