PHP & MySQL

Php er et programmeringssprog og MySQL er en database, men de hører sammen i næsten alle sammenhæng.

 

Delete MySQL PHP 7

$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

$db = new PDO(“mysql:host=”.$servername.”;dbname=”.$dbname,$username, $password);
$brugernavn = $_GET[“brugernavn”];
try
{
$statement = $db->prepare(“DELETE FROM `brugere` WHERE brugernavn=?”);
$statement->execute(array($brugernavn));
echo “Bruger er slettet $brugernavn”;
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}

//$statement->execute(array($brugernavn, $adgangskode));

Update MySQL with php 7

$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection

if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}

$sql = “UPDATE MyGuests SET lastname=’Doe’ WHERE id=2”;

if ($conn->query($sql) === TRUE) {
echo “Record updated successfully”;
} else {
echo “Error updating record: ” . $conn->error;
}

$conn->close();

Create MySQL PHP 7

$db = new PDO(“mysql:host=”.$servername.”;dbname=”.$dbname,$username, $password);

//insert

$brugernavn = $_POST[“brugernavn”];
$adgangskode = password_hash($_POST[“adgangskode”], PASSWORD_BCRYPT);

try
{
$statement = $db->prepare(“insert into brugere values(?,?)”);
$statement->execute(array($brugernavn, $adgangskode));
echo “Bruger oprettet”;
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}

//$statement->execute(array($brugernavn, $adgangskode));

Select MySQL PHP 7

$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;

$db = new PDO(“mysql:host=”.$servername.”;dbname=”.$dbname,$username, $password);

try
{
$statement = $db->prepare(“select navn from kunde”);
$statement->execute();
$rows = $statement->fetchAll();

foreach($rows as $bruger)
{
echo $bruger[“navn”];
}

}
catch(PDOException $exception)
{
echo $exception->getMessage();
}

Count a table

function CountTypetabel($type)
{

$sth = $db->prepare(“SELECT count(*) as total from Type WHERE typenavn =’$type’ “);
$sth->execute();
$result = $sth->fetchAll();

return $result[0][‘total’];
}

Function and Try /catch

function testkategori($testnavn)
{
try
{
include ‘../../Connections/cms.php’;
$statement = $db->prepare(“INSERT INTO Kategori values(?,?)”);
$statement->execute(array(”, $testnavn));

return “Succesfull!”;
}
catch(Exception $e)
{
return “Something error!”.$e;
}
}