PHP database

PHP MySQL connect to database

The free MySQL database is usually used through PHP.

Connect to a MySQL database

Before you can access and manipulate data in a database, you must create a connection to the database.

In PHP, this task is accomplished through the mysql_connect() function.

grammar

mysql_connect(servername,username,password);

Note: Although there are other parameters, the most important ones are listed above. Please visit the PHP MySQL reference manual provided by W3School  for more details.

example

In the example below, we store the connection in a variable ($con) for later use in the script. If the connection fails, the "die" part will be executed:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

// some code

?>

close connection

Once the script ends, the connection is closed. If you need to close the connection early, use the mysql_close() function.

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

// some code

mysql_close($con);
?>

A database has one or more tables.

Create database

The CREATE DATABASE statement is used to create a database in MySQL.

grammar

CREATE DATABASE database_name

In order for PHP to execute the above statement, we must use the mysql_query() function. This function is used to send queries or commands to the MySQL connection.

example

In the following example, we create a database named "my_db":

<?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);
?>

Create table

CREATE TABLE is used to create database tables in MySQL.

grammar

CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
.......
)

In order to execute this command, I have to add a CREATE TABLE statement to the mysql_query() function.

example

The following example shows how to create a table named "Persons" with three columns. The column names are "FirstName", "LastName" and "Age":

<?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 in my_db database
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);
?>

Important: Before creating a table, you must first select a database. Select the database through the mysql_select_db() function.

Note: When you create a database field of type varchar, you must specify the maximum length of the field, for example: varchar(15).

MySQL data types

The following various MySQL data types are available:

 

Primary keys and auto-increment fields

Every table should have a primary key field.

Primary keys are used to uniquely identify rows in a table. Each primary key value must be unique in the table. Additionally, the primary key field cannot be empty because the database engine requires a value to locate the record.

Primary key fields are always indexed. There are no exceptions to this rule. You must index the primary key field so that the database engine can quickly locate the row given the key value.

The following example sets the personID field as the primary key field. The primary key field is usually an ID number, and is usually set using AUTO_INCREMENT. AUTO_INCREMENT will increment the value of this field one by one as new records are added. To ensure that the primary key field is not null, we must add the NOT NULL setting to the field.

example

$sql = "CREATE TABLE Persons 
(
personID int NOT NULL AUTO_INCREMENT, 
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)";

mysql_query($sql,$con);

PHP MySQL Insert Into

The INSERT INTO statement is used to insert new records into a database table.

Insert data into database table

The INSERT INTO statement is used to add new records to a database table.

grammar

INSERT INTO table_name
VALUES (value1, value2,....)

 You can also specify the columns into which you want to insert data:

INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)

Note: SQL statements are not case-sensitive. INSERT INTO is the same as insert into.

In order for PHP to execute this statement, we must use the mysql_query() function. This function is used to send queries or commands to the MySQL connection.

example

In the previous chapter, we created a table named "Persons" with three columns: "Firstname", "Lastname" and "Age". We will use the same table in this example. The following example adds two new records to the "Persons" table:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("INSERT INTO Persons (FirstName, LastName, Age) 
VALUES ('Peter', 'Griffin', '35')");

mysql_query("INSERT INTO Persons (FirstName, LastName, Age) 
VALUES ('Glenn', 'Quagmire', '33')");

mysql_close($con);
?>

Insert data from form into database

Now, we create an HTML form that inserts new records into the "Persons" table.

Here is this HTML form:

<html>
<body>

<form action="insert.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>
</html>

When the user clicks the submit button in the HTML form in the example above, the form data is sent to "insert.php". The "insert.php" file connects to the database and retrieves values ​​from the form through the $_POST variable. Then, the mysql_query() function executes the INSERT INTO statement, and a new record is added to the database table.

Here is the code for the "insert.php" page:

<?php
$con = mysql_connect("localhost","peter","abc123");
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)
?>

PHP MySQL Select

The SELECT statement is used to select data from the database.

Select data from database table

The SELECT statement is used to select data from the database.

grammar

SELECT column_name(s) FROM table_name

Note: SQL statements are not case-sensitive. SELECT is equivalent to select.

In order for PHP to execute the above statement, we must use the mysql_query() function. This function is used to send queries or commands to MySQL.

example

The following example selects all data stored in the "Persons" table (the * character selects all data in the table):

<?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");

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

mysql_close($con);
?>

The above example stores the data returned by the mysql_query() function in the $result variable. Next, we use the mysql_fetch_array() function to return the first row from the recordset as an array. Each subsequent call to the mysql_fetch_array() function returns the next row in the recordset. The while loop statement loops through all records in the recordset. To output the value of each row, we use PHP's $row variables ($row['FirstName'] and $row['LastName']).

Output of the above code:

Peter Griffin
Glenn Quagmire

Display results in HTML table

The following example selects the same data as the above example, but displays the data in an HTML table:

<?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");

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

PHP MySQL Where child clause

To select data that matches specified criteria, add a WHERE clause to the SELECT statement.

WHERE child clause

To select data that matches specified criteria, add a WHERE clause to the SELECT statement.

grammar

SELECT column FROM table
WHERE column operator value

Note: SQL statements are not case-sensitive. WHERE is equivalent to where.

In order for PHP to execute the above statement, we must use the mysql_query() function. This function is used to send queries and commands to the SQL connection.

example

The following example will select all rows from the "Persons" table with FirstName='Peter':

<?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 />";
  }

?>

 

PHP MySQL Order By Keywords

The ORDER BY keyword is used to sort data in a recordset.

ORDER BY keyword

The ORDER BY keyword is used to sort data in a recordset.

grammar

SELECT column_name(s)
FROM table_name
ORDER BY column_name

Note: SQL is not case sensitive. ORDER BY is equivalent to order by.

example

The following example selects all data stored in the "Persons" table and sorts the results based on the "Age" column:

<?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 ORDER BY age");

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

mysql_close($con);
?>

PHP MySQL Update

The UPDATE statement is used to modify data in a database table.

Update data in database

The UPDATE statement is used to modify data in a database table.

grammar

UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value

Note: SQL is not case sensitive. UPDATE is equivalent to update.

In order for PHP to execute the above statement, we must use the mysql_query( function. This function is used to send queries and commands to the SQL connection.

example

Earlier in this tutorial, we created a table named "Persons". It looks similar to this:

The following example updates some data in the "Persons" table:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("UPDATE Persons SET Age = '36'
WHERE FirstName = 'Peter' AND LastName = 'Griffin'");

mysql_close($con);
?>

 

PHP MySQL Delete From

DELETE FROM statement is used to delete rows from a database table.

Delete data in database

DELETE FROM statement is used to delete records from a database table.

grammar

DELETE FROM table_name
WHERE column_name = some_value

Note: SQL is not case sensitive. DELETE FROM is equivalent to delete from.

In order for PHP to execute the above statement, we must use the mysql_query( function. This function is used to send queries and commands to the SQL connection.

example

Earlier in this tutorial, we created a table named "Persons". It looks similar to this:

The following example deletes all records with LastName='Griffin' in the "Persons" table:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("DELETE FROM Persons WHERE LastName='Griffin'");

mysql_close($con);
?>

 

PHP Database ODBC

ODBC is an Application Programming Interface (API) that enables us to connect to a data source (such as an MS Access database).

Create ODBC connection

Through an ODBC connection, you can connect to any database on any computer in your network, as long as the ODBC connection is available.

This is how to create an ODBC connection to MS Access data:

  1. Open Administrative Tools in Control Panel
  2. Double-click the data source (ODBC)  icon
  3. Select the System  DSN tab
  4. Click the " Add " button in the System DSN tab
  5. Select  Microsoft Access Driver . Click Done .
  6. On the next screen, click " Select " to locate the database.
  7. Choose a data source name (DSN) for this database .
  8. Click OK .

Please note that this configuration must be completed on the same computer as your website. If your computer is running Internet Information Server (IIS), the above instructions will work, but if your website is on a remote server, you must have physical access to the server or ask your hosting provider to set it up for you. DSN.

Connect to ODBC

The odbc_connect() function is used to connect to ODBC data sources. This function has four parameters: data source name, user name, password, and optional pointer type parameters.

The odbc_exec() function is used to execute SQL statements.

example

The following example creates a connection to the DSN named northwind without a username or password. Then create and execute a SQL statement:

$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers"; 
$rs=odbc_exec($conn,$sql);

Retrieve records

The odbc_fetch_row() function is used to return records from the result set. Returns true if rows can be returned, false otherwise.

This function takes two parameters: an ODBC result identifier and an optional line number:

odbc_fetch_row($rs)

 

Guess you like

Origin blog.csdn.net/m0_61981943/article/details/131938158