Labels

Android (1) bash (2) boost (2) C (34) C++ (2) cheatsheet (2) CLion (6) css (3) Debian (33) DL (17) Docker (2) Dreamweaver (2) Eclipse (3) fail2ban (4) git (5) GitHub (4) Hacking (3) html (8) http (1) iOS (1) iPad (1) IRC (1) Java (31) javascript (3) Linux (167) Mac (19) Machine Learning (1) mySQL (48) Netbeans (4) Networking (1) Nexus (1) OpenVMS (6) Oracle (1) Pandas (3) php (16) Postgresql (8) Python (9) raid (1) RedHat (14) Samba (2) Slackware (47) SQL (14) svn (1) tar (1) ThinkPad (1) Virtualbox (3) Visual Basic (1) Visual Studio (1) Windows (2)

Sunday, 20 September 2020

PHP example MySQL connection and query.

 

<!DOCTYPE html>
<html>
<body>

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "db_name";


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{

die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, field1,field2 FROM tableName";
$result = $conn->query($sql);

if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo "<br> id: ". $row["id"]. " - Field1: ". $row["field1"]. " - Field2:" . $row["field2"] . "<br>";
}
}
else
{
echo "0 results";
}

$conn->close();
?>

</body>
</html>

The connection details can of course be held in a separate file, with the following being added to the above php file;

<?php require_once('Connections/mysqltest.php'); ?>

The mysqltest.php file would look something like;
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "db_name";
$mysqltest = mysql_pconnect($servername, $usernamet, $password) or trigger_error(mysql_error(),E_USER_ERROR);
?>

No comments:

Post a Comment

Note: only a member of this blog may post a comment.