an example to insert some data in to the mysql datasqbase using php

22
An example to insert some data in to the MySQL database using PHP 1. Create a Index.php page in a new folder(“764”) created under public_html folder present in your home directory To use a PHP script on your web page, you just need to end the file name with .php and make sure the permissions on the file are set correctly. Any files to be accessed by the web server must be publically readable, but none of your PHP files (nor the directory containing them) may be group or publically writable. Following are the commands you can use for setting the permissions in linux: chmod 755 public_html chmod 644 public_html/764/index.php The PHP page will have two simple text boxes for the user to enter some data in to it. Label them to be Firstname and Lastname. INDEX.PHP <html> <body> <h1>A small example page to insert some data in to the MySQL database using PHP</h1> <form action="insert.php" method="post"> Firstname: <input type="text" name="fname" /><br><br> Lastname: <input type="text" name="lname" /><br><br> <input type="submit" /> </form> </body> </html> We also need to make sure that the form method attribute is “post” so as to access the data being entered in a reliable way in the next page being directed “insert.php” so that the data being entered in the textboxes can then be saved to the database in the “insert.php” page.

Upload: ramkrishan-swami

Post on 28-Nov-2015

82 views

Category:

Documents


0 download

DESCRIPTION

Some Topics 4 sql

TRANSCRIPT

Page 1: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

An example to insert some data in to the MySQL database using PHP

1. Create a Index.php page in a new folder(“764”) created under public_html folder present in your home directory

To use a PHP script on your web page, you just need to end the file name with .php and make sure the permissions on the file are set correctly. Any files to be accessed by the web server must be publically readable, but none of your PHP files (nor the directory containing them) may be group or publically writable. Following are the commands you can use for setting the permissions in linux:

chmod 755 public_htmlchmod 644 public_html/764/index.php

 The PHP page will have two simple text boxes for the user to enter some data in to it. Label them to be Firstname and Lastname.

INDEX.PHP

<html><body><h1>A small example page to insert some data in to the MySQL database using PHP</h1><form action="insert.php" method="post">Firstname: <input type="text" name="fname" /><br><br>Lastname: <input type="text" name="lname" /><br><br> <input type="submit" /></form></body></html> We also need to make sure that the form method attribute is “post” so as to access the data being entered in a reliable way in the next page being directed “insert.php” so that the data being entered in the textboxes can then be saved to the database in the “insert.php” page.

Page 2: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

  

Page 3: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

2. To connect to MySQL :-

Before you can access your MySQL database, you must contact the system administrators to request an account.

Once the administrators have notified you that your account has been created, you may connect using the following instructions.

Go to http://mysql.cis.ksu.edu/phpmyadmin and type your MySQL ID and password being given.

 

 

Page 4: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

3. Now enter the new table name “nametable” , number of fields in that table as “2” and hit GO button.

 

Page 5: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

4. Enter the field names to be “firstname” and “lastname” and keep the length attributes to be “20” for both the fields. The default type of VARCHAR is kept as it is.

 

Page 6: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

5. After the table fields are being created, the following screen will be shown to you.

Page 7: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

6. Now we need to make a connection to the MySQL database and then send this entered data from our textboxes. For that we create a new PHP page “insert.php” and use the following connection strings to the connection variable $con After making a connection, a SQL query is being written to enter this data in to the MySQL database being created (“nametable”) To tell the user that the data is being entered we set the echo to "1 record added"INSERT.PHP<html><body>  <?php$con = mysql_connect("mysql.cis.ksu.edu","cis_id","password");if (!$con)  {  die('Could not connect: ' . mysql_error());  } mysql_select_db("cis_id", $con); $sql="INSERT INTO nametable (fname, lname)VALUES('$_POST[fname]','$_POST[lname]')"; if (!mysql_query($sql,$con))  {  die('Error: ' . mysql_error());  }echo "1 record added"; mysql_close($con)?></body></html> 

 

Page 8: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

7. Now type the index page URL in your browser and enter some data in to the textboxes. Submit the Query.

 

We will then be shown the confirmation page after the data is being

entered. 

 

Page 9: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

8. For browsing the data, you need to click on Database: cis_id on top of the page (http://mysql.cis.ksu.edu/phpmyadmin)  to get to the database tables page. Then click on the browse button as shown below, beside the “nametable” which you have already created to browse through the entered data.

                                                                                                                  

Page 10: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

9. The following screen then shows us the data being entered in to the MySQL database table being created. 

 

Lesson 19: Insert data into a database

In this lesson, we look at how you can insert data into the database directly from your PHP scripts.

Insert data using SQL

You use SQL to insert data in a database in the same way that you can use SQL to create databases and tables. The syntax of the SQL query is:

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

Page 11: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

As you can see, you can update multiple columns in the SQL statement by specifying them in a comma-separated list. But of course, it is also possible to specify just one column and one value. The columns that are not mentioned in the SQL statement will just be empty.

Example: Insert a new person in the table

In this example we use the database from lesson 18. Let's say we want to insert a person into the database. It could be the person Gus Goose with the phone number 99887766 and 1964-04-20 as the date of birth.

The SQL statement would then look like this:

$strSQL = "INSERT INTO people(FirstName,LastName,Phone,BirthDate) VALUES('Gus','Goose','99887766 ','1964-04-20')";

mysql_query($strSQL) or die(mysql_error());

As you can see, SQL statements can get quite long, and you can easily lose track. Therefore, it can be an advantage to write the SQL statement in a slightly different way:

strSQL = "INSERT INTO people(";

strSQL = strSQL . "FirstName, ";strSQL = strSQL . "LastName, "strSQL = strSQL . "Phone, ";strSQL = strSQL . "birth) ";

strSQL = strSQL . "VALUES (";

strSQL = strSQL . "'Gus', ";strSQL = strSQL . "'Goose', ";strSQL = strSQL . "'99887766', ";

strSQL = strSQL . "'1964-04-20')"; mysql_query($strSQL) or die(mysql_error());

This way, the SQL statement is built up by splitting the sentence into small parts and then putting those parts together in the variable $strSQL.

In practice, it makes no difference which method you choose, but once you start working with larger tables, it's crucial that you always keep track, so choose the method you find most convenient.

Try running the following code to insert Gus Goose into the database:

<html><head><title>Insert data into database</title>

Page 12: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

</head><body><?php

// Connect to database servermysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

// Select databasemysql_select_db("mydatabase") or die(mysql_error());

// The SQL statement is built

$strSQL = "INSERT INTO people(";

$strSQL = $strSQL . "FirstName, ";$strSQL = $strSQL . "LastName, ";

$strSQL = $strSQL . "Phone, ";$strSQL = $strSQL . "BirthDate) ";

$strSQL = $strSQL . "VALUES(";

$strSQL = $strSQL . "'Gus', ";

$strSQL = $strSQL . "'Goose', ";$strSQL = $strSQL . "'99887766', ";

$strSQL = $strSQL . "'1964-04-20')";

// The SQL statement is executed mysql_query($strSQL) or die (mysql_error());

// Close the database connectionmysql_close();?>

<h1>The database is updated!</h1></body></html>

Save user input into a database

Often you want to save user input in a database.

As you've probably already figured out, this can be done by creating a form as described in lesson 11 - where the values from the form fields can be inserted in the SQL statement. Suppose you have a simple form like this:

<form action="insert.php" method="post"><input type="text" name="FirstName" /><input type="submit" value="Save" />

</form>

Page 13: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

The form submits to the file insert.php where you, as shown in lesson 11, can get the user's input by requesting the form content. In this particular example, an SQL statement could look like this:

strSQL = "INSERT INTO people(FirstName) values('" . $_POST["FirstName"] . "')"

In the same way, it is possible to retrieve data from cookies, sessions, query strings, etc.

Most common beginner mistakes

In the beginning, you will probably get a lot of error messages when you try to update your databases. There is no room for the slightest inaccuracy when you work databases. A misplaced comma can mean the database is not being updated, and you get an error message instead. Below, we describe the most common beginner mistakes.

Wrong data types

It is important that there is consistency between the type of data and column. Each column can be set to a data type. The screenshot below shows the data types for the table "people" in our example.

An error occurs if you, for example, attempt to insert text or numbers in a date field. Therefore, try to set the data types as precisely as possible.

Below is the most common data types listed:

Setting Data Type

CHARText or combinations of text and numbers. Can also be used for numbers that are not used in calculations (e.g., phone numbers).

Up to 255 characters - or the length defined in the "Length"

TEXT Longer pieces of text, or combinations of text and numbers. Up to 65,535 characters.

INT Numerical data for mathematical calculations. 4 bytes.

Page 14: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

DATE Dates in the format YYYY-MM-DD 3 bytes.

TIME Time in the format hh:mm:ss 3 bytes.

DATETIME Date and time in the format YYYY-MM-DD hh:mm:ss 8 bytes.

SQL statements with quotes or backslash

If you try to insert text that contains the characters single quote ('), double quote (") or backslash (\), the record may not be inserted into the database. The solution is to add backslashes before characters that need to be quoted in database queries.

This can be done with the function  addslashes this way:

<?php

$strText = "Is your name O'Reilly?";$strText = addslashes($strText);

?>

All single quotes ('), double quotes (") and backslashs (\) will then get an extra backslash before the character. This would only be to get the data into the database, the extra \ will not be inserted. Please note that PHP runs  addslashes on all $_GET, $_POST, and $_COOKIE data by default. Therefore do not use  addslashes on strings that have already been escaped.

In the next lesson you will learn to retrieve data from your database. But first, try to insert some more people in your database (as shown in the example above with Gus Goose).

Inserting Data into SQL Server Database using Csharp and ASP.NET

Page 15: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

In this article you will see how to insert some values in sql

server tables, very usefull to many programs.add to favorites

set as viewed

add a note

 54 

 

 

 

  Like   (107)

  (56)

Introduction:

The data storage plays a very important role while developing any application. This

tutorial will cover that how to create a SQL server express database with VS2008 and

make a connection with it. The tutorial will also cover the data insertion using the

ASP.NET and C#.

o Step-1: Create ASP.NET Controls

o Step-2: Create Database and Table in SQL Server

o Step-3: Create Connection in web.config

Create ASP.NET Controls:

Open Visual Studio 2008; now go on File Menu -> Open New Website, after that open

default.aspx page. On default page take & drop Textboxes, Button, as shown in given

figure 1.

Figure 1: Initial UI with some fields

Listing 1: ASP.NET Script providing input for database insert

Page 16: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

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

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>MrBool.com – Interacting with Database</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <table style="width:900px; height:100px; vertical-align:top">

    <tr>

    <td style="width:600px; padding-left:200px">

    <b style="padding-left:65px">id: </b>

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />

        <b style="padding-left:40px">Name:</b>

        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />

        <b>Designation:</b>

        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />

        <b style="padding-left:5px">Mobile_No:</b>

        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox><br />

        <b style="padding-left:26px">Address:</b>

        <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox><br />

        <asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click"/>

       

    </td>

    </tr>

    </table>

    

    </div>

    </form>

</body>

Page 17: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

28

29

30

</html>

Create Database and Table in SQL Server:

Let’s now start with creating the database table using visual studio 2008. Open the

solution explorer right click on website add new item – open item templates select SQL

Server Database click on add button after that show message box click on “Yes” button.

Now follow the following steps to create the table:

1. Go on Server explorer open database.mdf and right click on table

2. Create new table

3. Now insert field as Id(Int), Name(varchar(50)), Designation(varchar(50)),

Mobile_No(Int), Address(varchar(50)).

Figure 2: SQL Server Database Table with given Columns

After create database go on default.aspx page and double click on Submit Button and

write down some code:

Listing 2: C# code to insert data in database1 using System.Data.SqlClient;

Page 18: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

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

protected void Button1_Click(object sender, EventArgs e)

    {

        SqlConnection cnn = new SqlConnection();

        cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlconnection "].ConnectionString;

        cnn.Open();

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "select * from  TableName";

        cmd.Connection = cnn;

        SqlDataAdapter da = new SqlDataAdapter();

        da.SelectCommand = cmd;

        DataSet ds = new DataSet();

        da.Fill(ds, " TableName ");

        SqlCommandBuilder cb = new SqlCommandBuilder(da);

        DataRow drow = ds.Tables["TableName"].NewRow();

        drow["id"] = TextBox1.Text;

        drow["Name"] = TextBox2.Text;

        drow["Designation"] = TextBox3.Text;

        drow["Mobile_No"] = TextBox4.Text;

        drow["Address"] = TextBox5.Text;

        ds.Tables["TableName "].Rows.Add(drow);

        da.Update(ds, " TableName ");

        string script = @"<script language=""javascript"">

        alert('Information have been Saved Successfully.......!!!!!.');

       </script>;";

        Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);

    }

Page 19: An Example to Insert Some Data in to the MySQL DataSqbase Using PHP

29

30

Create Connection in Web.Config:

Now you have to create a web.config connection entry to connect to database. Note that

this connection requires a Data Source, DB File Name, and provider name.

Listing 3: Web.config Entry for Connection Details

1

2

3

4

<connectionStrings>

<add name="sqlconnection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"providerName="System.Data.SqlClient"/>

  </connectionStrings>

    <system.web>

Conclusion:

By following the above steps you can create a SQL express connection and make a small

database application. My future articles will also cover some advance topics with

database and ASP.NET.

Please comment below in case of any queries.

Read more: http://mrbool.com/inserting-data-into-sql-server-database-using-csharp-and-asp-net/25091#ixzz2poXJBHT4