{PHP} Comes In Handy

Lige den funktion du behøver..!

Brug browserens indbyggede søgefunktion (Ctrl + f) for at lede efter et udtryk eller key-word

F.eks.

DataTable
eller
SqlConnection

<?php

//SQL, objekt

$conn = new mysqli('host', 'user', 'password', 'database');
$conn->set_charset('utf8');
$sqlStr = "SELECT * FROM table";
$result = $conn->query($sqlStr);
$antalReakker = $result->num_rows;
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
    echo $row['kolonnenavn'];
}

<?php

//Eksempel

$host = 'localhost';
$user = 'root';
$password = 'root'; // ER TOM FOR WINDOWS-BRUGERE, ROOT FOR MAC-BRUGERE (LOCALHOST)
$database ='db_hi_fi';

$conn = new mysqli($host, $user, $password, $database);

$sqlStr = "SELECT * FROM categories";
$result = $conn->query($sqlStr);
$antalReakker = $result->num_rows;

while($row = $result->fetch_array(MYSQLI_ASSOC))
{
    echo '<p>.'.$row['category_name'].'</p>';
}

echo '<p>antal: '.$antalReakker.'</p>';


<?php

//SQL, procedural

$conn = mysqli_connect('host', 'user', 'password', 'database');
mysqli_set_charset($conn, 'utf8');
$sqlStr = "SELECT * FROM table";
$result = mysqli_query($conn, $sqlStr);
$antal = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
    echo $row['kolonnenavn'];
}
############ CRUD #############
//-> Fil: db_connection.php
<?php
	$host = "localhost";
	$user = "root";
	$password = "";
	$database = "rts_crud";
	
	$connection = mysqli_connect ($host, $user,$password, $database) or die("ingen forbindelsen til databasen, ".$database);
	
	$charset = mysqli_set_charset ($connection, "utf8");
?>

//-> Fil: show.php (Vis kun en enkel raekke)
<?php
	$id = $_GET['id'];

	$sql = "SELECT * FROM artikler WHERE Id=$id";
	$result = mysqli_query ($connection, $sql);

	$row = mysqli_fetch_array($result);
	$date_timestamp = strtotime($row['OprettetDen']);
	$date_string = date('j/n-Y,H:i:s', $date_timestamp);
		//echo "<pre>";  print_r($row);  echo "</pre>";
		echo "<article>";
		
		echo "<h2>$row[Titel]</h2>";
		echo "<p>";
		echo "<b>$row[Rubrik]</b><br>";
		echo $row["Indhold"];
		echo "</p>";
		echo "<time>$date_string</time>";
		echo "<br><a href='index.php'>Tilbage til forsiden</a>";
		echo "</article>";
		

?>


//-> Fil: delete.php
<?php 
	include ('includes/db_connection.php'); ?>
	
	<?php
	$id = $_GET['id'];

	$sql = "DELETE FROM artikler WHERE Id=$id";
	$result = mysqli_query ($connection, $sql)or die(mysqli_error($connection));
	
	header("Location: index.php");
	exit;
?>


//-> new.php
<?php
	include ('includes/db_connection.php');

	//test!
	//echo "<pre>"; print_r($_POST); echo "</pre>";
	
	if (isset($_POST['submit']))
	{
		$titel = $_POST['Titel'];
		$rubrik = $_POST['Rubrik'];
		$indhold = $_POST['Indhold'];
		
		$sql = "INSERT INTO artikler (Titel, Rubrik, Indhold) VALUES ('$titel', '$rubrik', '$indhold')";
		
		mysqli_query($connection, $sql) or die(mysqli_error($connection));
	}
?>

	<form method="post">
		Titel:<br>
		<input type="text" name="Titel" value="" /><br>
		Rubrik:<br>
		<input type="text" name="Rubrik" value="" /><br>
		Indhold:<br>
		<textarea name="Indhold" rows="4" cols="20"></textarea><br>
		<input type="submit" value="Opret" name="submit" />
 	</form>
    
    	<a href='index.php'>Tilbage til forsiden</a>


//-> Fil: edit.php
<?php
	include ('includes/db_connection.php');
	if(isset($_GET['id']))
	{
		$id = $_GET['id'];
		$titel = "";
		$rubrik = "";
		$indhold = "";

	if(isset($_POST['submit']))
	{
		$titel = $_POST['Titel'];
		$rubrik = $_POST['Rubrik'];
		$indhold = $_POST['Indhold'];
		
		$sql = "UPDATE artikler SET Titel = '$titel', Rubrik = '$rubrik', Indhold = '$indhold' WHERE Id=$id";
		mysqli_query($connection, $sql);
	}
	else
	{
		$sql = "SELECT * FROM artikler WHERE Id=$id";
		$result = mysqli_query ($connection, $sql);
		$row = mysqli_fetch_array($result);
		
		$titel = $row['Titel'];
		$rubrik = $row['Rubrik'];
		$indhold = $row['Indhold'];
	}
}	
?>
	<form method="POST">
		Titel:<br>
		<input type="text" name="Titel" value="<?php echo $titel ?>" /><br>
		Rubrik:<br>
		<input type="text" name="Rubrik" value="<?php echo $rubrik ?>" /><br>
		Indhold:<br>
		<textarea name="Indhold" rows="4" cols="20"><?php echo $indhold ?></textarea><br>
		<input type="submit" value="Opret" name="submit" />
 	</form>
    
    	<form method="get" action="index.php">
    		<input type="submit" value="Tilbage"/>
        </form>
<?php
session_start();
include_once("connect.php");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Relationelle databaser</title>

<script type="text/javascript" language="javascript">
function gaaTilLoginForm()
{
	window.location = "admin/index.php";
}
</script>

</head>
<body>
<div style="clear:both;margin:2px;padding:12px;border:1px dotted white;color:#0F0;">
	<p><a href="?">Tilbage til start</a></p>
	<h3>Vi skal lave et site site der kan vise billeder fra forskellige begivenheder.</h3>
    <h3>Vi skal også se hvem der har taget det aktuelle foto.</h3>
    <h3>Vi skal bruge INNER JOIN eller LEFT JOIN</h3>
    <h3>Hvem må hvad? Vi ser på bruger - roller (I login)</h3>
</div>
<?php
if( isset($_GET['katKey']) && ($_GET['method'] == "innerJoin") )
{
	$katKey=$_GET['katKey'];
	$forsp="SELECT billeder.billednavn, kategori.kategorinavn, fotograf.navn FROM billeder 
			INNER JOIN kategori ON billeder.FK_kategori_noegle = kategori.kategori_noegle
			INNER JOIN fotograf ON fotograf.FK_billeder_id = billeder.id
			WHERE billeder.FK_kategori_noegle = ".(int)$katKey."";
	
	$result=mysqli_query($conn, $forsp);
	$antal = mysqli_num_rows($result);
	echo '<p>Antal poster (rækker): '.$antal.'</p>';
	
	while($row=mysqli_fetch_array($result, MYSQLI_ASSOC))
	{
		echo "<div style=\"margin:2px;padding:2px;float:left;\">";
			echo "<img src=\"images/".$row['billednavn']."\" 
			title=\"".$row['kategorinavn']."\" alt=\"".$row['billednavn']."\" /><p>".$row['billednavn'].". 
			Fotograf: <b>".$row['navn']."</b></p>";
		echo "</div>";
	}
echo "<div style=\"clear:both;margin:2px;padding:2px;border-top:1px dotted white;\">
<h2>Du valgte INNER JOIN</h2><p><pre>".$forsp."</pre></p></div>";
}

if( isset($_GET['katKey']) && ($_GET['method'] == "leftJoin") )
{
	$katKey=$_GET['katKey'];
	$forsp="SELECT billeder.billednavn, kategori.kategorinavn, fotograf.navn FROM billeder 
			LEFT JOIN kategori ON billeder.FK_kategori_noegle = kategori.kategori_noegle
			LEFT JOIN fotograf ON fotograf.FK_billeder_id = billeder.id
			WHERE billeder.FK_kategori_noegle = ".(int)$katKey."";
	
	$result=mysqli_query($conn, $forsp);
	$antal = mysqli_num_rows($result);
	echo '<p>Antal poster (rækker): '.$antal.'</p>';
	while($row=mysqli_fetch_array($result, MYSQLI_ASSOC))
	{
		echo "<div style=\"margin:2px;padding:2px;float:left;\">";
			echo "<img src=\"images/".$row['billednavn']."\" title=\"".$row['kategorinavn']."\" alt=\"".$row['billednavn']."\" /><p>".$row['billednavn'].". Fotograf: <b>".$row['navn']."</b></p>";
		echo "</div>";
	}
echo "<div style=\"clear:both;margin:2px;padding:2px;border-top:1px dotted white;\">
<h2>Du valgte LEFT JOIN</h2><p><pre>".$forsp."</pre></p></div>";
}

?>
<div style="margin:2px;padding:12px;float:left; border:1px solid white;">
    <h2>Se billeder fra...(med INNER JOIN)</h2>
    <p>&#8250; <a href="?katKey=22&method=innerJoin">Sommerferien</a></p>
    <p>&#8250; <a href="?katKey=17&method=innerJoin">Vinterferien</a></p>
    <p>&#8250; <a href="?katKey=12&method=innerJoin">Fødselsdagen</a></p>
    <p>&#8250; <a href="?katKey=404&method=innerJoin">En begivenhed ikke oprettet endnu...</a></p>
</div>
<div style="margin:2px;padding:12px;float:left; border:1px solid white;">
    <h2>Se billeder fra...(med LEFT JOIN)</h2>
    <p>&#8250; <a href="?katKey=22&method=leftJoin">Sommerferien</a></p>
    <p>&#8250; <a href="?katKey=17&method=leftJoin">Vinterferien</a></p>
    <p>&#8250; <a href="?katKey=12&method=leftJoin">Fødselsdagen</a></p>
    <p>&#8250; <a href="?katKey=404&method=leftJoin">En begivenhed ikke oprettet endnu...</a></p>
</div>
<div style="margin:2px;padding:12px;float:left; border:1px solid white;clear:both;">
	<?php
	// er man logget ind?
    
    if(isset($_SESSION["rolle_id"]))
	{
		$brugernavn = $_SESSION["brugernavn"];
    	$rolle = $_SESSION["rolle_id"];
		$rollebeskrivelse = $_SESSION["rollebeskrivelse"];
	
		?>
        <form action="admin/logud.php" method="post">
        	<input type="submit" name="logud" value="Log ud" />
    	</form>
        <h2>Velkommen, <?php echo $brugernavn; ?></h2>
        <p>Du har rolle nr <?php echo $rolle; ?> (<?php echo $rollebeskrivelse; ?>)</p>
    	
		<table>
        	<tr>
            	<td><a href="admin/admin.php?billeder">Billeder: </a></td>
                <td>Slette billeder</td>
                <td>Uploade billeder</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td><a href="admin/admin.php?kategorier">Kategorier: </a></td>
                <td>Slette kategorier</td>
                <td>Oprette kategorier</td>
                <td>Omdøbe kategorier</td>
            </tr>
            <tr>
                <td><a href="admin/admin.php?fotografer">Fotografer: </a></td>
                <td>Slette fotografer</td>
                <td>Oprette fotografer</td>
                <td>Rette fotografer</td>
            </tr>
            <tr>
                <td><a href="admin/admin.php?bruger">Bruger: </a></td>
                <td>Slet profil (<?php echo $brugernavn; ?>)</td>
                <td>Ret profil</td>
                <td>&nbsp;</td>
            </tr>
        </table>
		<?php
	}else{
	?>
         <input type="submit" name="logud" value="Log ind" onclick="gaaTilLoginForm();" />
    <?php
	}
	?>
</div>
</body>
</html>
// eksempel på brug af params
function getInfoFromDB($id)
	{
		if ($stmt = $this->DB->prepare("
			SELECT SQL_CACHE infoTable.Id, infoTable.Username, infoTable.UserImage, infoTable.UserCoverImage, infoTable.StamId, infoTable.CatId, infoTable.AboutMe, infoTable.Homepage, infoTable.Gender, infoTable.Born
			FROM infoTable WHERE Id=?
		"))
	 	{
			$stmt->bind_param('i', $id);
			$stmt->execute();
			$stmt->store_result();
			$stmt->bind_result($userId, $username, $userImage, $userCoverImage, $stamId, $catId, $aboutMe, $homepage, $gender, $born);
			$antal=$stmt->num_rows();
			if($antal >=1)
			{
				while($stmt->fetch())
				{
					$arr[$userId] = array(
					"username" => $username,
					"userImage" => $userImage,
					"userCoverImage" => $userCoverImage,
					"stamId" => explode(",",$stamId),
					"catId" => explode(",",$catId),
					"userId" => (int)($userId),
					"aboutMe" => nl2br($aboutMe),
					"homepage" => $homepage,
					"gender" => $gender,
					"born" => $born
					);
				}
			}
		}
		return $arr;
	}
<?php //simplexml_load_file ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Udskriv XML Opgaver</title>
</head>
<body>
	<section>
    	<?php
			$rod = simplexml_load_file('xml_opret_opgave_1.xml');
			echo $rod->navn;

 			$oplysninger = simplexml_load_file('xml_opret_opgave_2.xml');
		?>
    </section>
     <section>
     	<h3><?php echo $oplysninger->person->navn; ?></h3>
       	<p>Har hårfarven: <?php echo $oplysninger->person->haarfarve;?></p>
    </section>
  	<section>
    	<?php
			$biler = simplexml_load_file('xml_opret_opgave_3.xml');
			echo '<h2>Producent: '.$biler->producent->producentnavn .'</h2>';
			
			foreach($biler->producent as $bil)
			{
				foreach($bil as $element)
				{
					 echo '<p>'.$element->type.' ';
					 echo $element->farve.'</p>';
				}	
			}
		?>
  	</section>
    <section>
        <hr>
        <?php
            $skoler = simplexml_load_file('xml_opret_opgave_4.xml');
            foreach($skoler->skole as $skole)
            {
                echo '<h2>Skole: '.$skole->skolenavn .'</h2>';
                
                foreach($skole->klasse as $element)
                {
                    echo '<p><b>Klassenavn:'.$element->klassenavn.'</b></p>';
                    
                    foreach($element->elever as $element)
                    {
                        foreach($element->elev as $element)
                   		{
							echo '<p>Elev for-og efternavn: '.$element->fornavn.' ';
                        	echo $element->efternavn.'</p>';
						}
                    }
                    echo '<hr>';
                }
            }			
        ?>
  	</section>
</body>
</html>