PHP之mysql数据库

1.连接数据库

mysql -u root -p

2.显示有几个数据库

show databses

3.创建数据库

<?php
	

	$con = mysql_connect ( "localhost", "root", "a76d290e04" );
	if (! $con) {
		die ( 'Could not connect: ' . mysql_error () );
	}
	
	if (! $con) {
		die ( 'Could not connect: ' . mysql_error () );
	}
	
	if (mysql_query ( "CREATE DATABASE my_db", $con )) {
		echo "Database created";
	} else {
		echo "Error creating database: " . mysql_error ();
	}
	
	mysql_select_db ( "my_db", $con );
	$sql = "CREATE TABLE Persons 
	(
	FirstName varchar(15),
	LastName varchar(15),
	Age int
	)";
	
	mysql_query ( $sql, $con );
	
	mysql_close ( $con );
	  
?>

二.插入数据

<body>

<?php

	$con = mysql_connect ( "localhost", "root", "a76d290e04" );
	if (! $con) {
		die ( 'Could not connect: ' . mysql_error () );
	}
	
	if (! $con) {
		die ( 'Could not connect: ' . mysql_error () );
	}
	
	mysql_select_db ( "my_db", $con );
	
	$sql = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
	
	if (! mysql_query ( $sql, $con )) {
		die ( 'Error: ' . mysql_error () );
	}
	echo "1 record added";
	
	mysql_close ( $con );
?>

<form action="index.php" method="post">Firstname: <input type="text"
	name="firstname" /> Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" /> <input type="submit" /></form>

</body>


三.查询数据

<?php

	$con = mysql_connect ( "localhost", "root", "a76d290e04" );
	if (! $con) {
		die ( 'Could not connect: ' . mysql_error () );
	}
	
	if (! $con) {
		die ( 'Could not connect: ' . mysql_error () );
	}
	
	mysql_select_db ( "my_db", $con );
	
	$result = mysql_query("SELECT * FROM Persons");

	while ( $row = mysql_fetch_array ( $result ) ) {
		echo $row ['FirstName'] . " " . $row ['LastName'];
		echo "<br />";
}
	
	
	mysql_close ( $con );
?>



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。