Inserare date

postat acum 2 ani de Stefanescu Mihai in categorie PHP

Pot fi inserate date intr-o baza de date folosind functia PHP query() si SQL INSERT.

Iata si un exemplu simplu de insert:

<?php
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'parola';
$dbdb = "test";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbdb);
if( !$conn ){
  die('Nu ma pot conecta: ' . $conn->error());
}
$sql = 'INSERT INTO users(nume, adresa, varsta, data_inregistrarii) VALUES("Mihai", "str. x, nr. 73, bl.91, ap.314", 23, NOW() )';

$retval = $conn->query( $sql );

if( !$retval ){
  die('Nu am putut insera datele in baza de date: ' . $conn->error());
}

echo "Succes!";
$conn->close();
?>

Intr-o aplicatie reala datele sunt preluate de la utilizator printr-un formular, sunt validate si sanitizate, iar mai apoi sunt introduse in baza de date.

In exemplul de mai jos verific daca avem magic quotes pornit (magic quotes era o functie care rezolva problema ghilimelelor din string-uri) folosind functia get_magic_quotes_gpc() , daca nu este activata folosim functiaaddslashes().

<html>
<head>
<title>Adaugare inregistrare in baza de date MySQL</title>
</head>
<body>
<?php
if( $_SERVER['REQUEST_METHOD'] === 'POST' ){
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'parola';
$dbdb = 'test';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbdb);
if( !$conn ){
  die('Nu ma pot conecta: ' . $conn->error());
}

if( !get_magic_quotes_gpc() ){
   $nume = addslashes($_POST['username']);
   $adresa = addslashes ($_POST['adresa']);
}else{
   $nume = $_POST['username'];
   $adresa = $_POST['adresa'];
}
$varsta = $_POST['varsta'];

$sql = "INSERT INTO users(nume, adresa, varsta, data_inregistrarii) VALUES('{$nume}', '{$adresa}', '{$varsta}', NOW() )";

$retval = $conn->query( $sql );
if( !$retval ){
  die('Nu pot introduce datele in baza de date: ' . $conn->error());
}
echo "Succes!";
$conn->close();
}else{
?>
<form action="<?php $_PHP_SELF ?>" method="POST">
	<table width="400" border="0" cellspacing="1" cellpadding="2">
		<tr>
			<td width="100">Username</td>
			<td><input name="username" type="text" placeholder='Username-ul dorit' /></td>
		</tr>
		<tr>
			<td width="100">Adresa</td>
			<td><input name="adresa" type="text" placeholder='Adresa curenta' /></td>
		</tr>
		<tr>
			<td width="100">Varsta</td>
			<td><input name="varsta" type="text" placeholder="Varsta ta" /></td>
		</tr>
		<tr>
			<td width="100"> </td>
			<td> <input type="submit" value="Inregistrare" /> </td>
		</tr>
	</table>
</form>
<?php
}
?>
</body>
</html>

 

Sunt un tanar programator din Bucuresti ce lucreaza in PHP/Mysql (MySqli/PDO), Laravel, CodeIgniter, MySQL, PostgreSQL, Wordpress, HTML5/CSS3, Sass, Photoshop si multe altele.
Google+ Community Facebook Group
Acest articol a fost mutat de pe vechea platforma.
Pentru orice eroare aparuta la mutare va rog sa ma contactati!