Tag Archives: MySQL Create
MYSQL Where
The WHERE clause is used for extracting only those records that fulfill a specified criterion. If you wanted to select only certain entries of your table, then you would use the keyword WHERE. WHERE lets you specify requirements that entries must meet in order to be returned in the MySQL result. Those entries that do not pass the test will be left out.Syntax:
1 2 3 4 5 |
SELECT column_name(s) FROM table_name WHERE column_name operator value |
To get PHP to execute the statement above you must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.The following example selects all rows from the Persons table where FirstName=’Peter’:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons
WHERE FirstName='Peter'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?>
|
MySQL Create
The CREATE DATABASE statement is used to create a database in MySQL:
1 |
CREATE DATABASE database_name |
To get PHP to execute the statement above you should use the mysql_query() function. This function is used to send a query or command to a MySQL connection.This example code shows how to create a database named “my_db”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?php
$con = mysql_connect("localhost","peter","abc123");
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_close($con);
?>
|
To create a table in mysql, use The CREATE TABLE statement:
CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... )
Also, the CREATE TABLE statement should be added to the mysql_query() function in order to execute the command.The following example creates a table named “Persons”, with three columns. The column names will be “FirstName”, “LastName” and “Age”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
|







