Mysql insert or die php

Блог

Допустимо ли делать что-то подобное, я никогда не вижу более 1 оператора or:

 $insert = 'INSERT into fhours (' .$cols . ') VALUES ('.$query.')'; $update = sprintf("UPDATE fhours SET %s WHERE fname='$fname' AND lname='$lname'", $field_list); $result = $db->query($update) or $db->query($insert) or die('uhoh');`  

Комментарии:

1. почему бы вам не встроить логику в свой PHP-скрипт? оператор if else?

2. @Rob, нет причин не использовать if / else, просто интересно, приемлем ли приведенный выше код и можно ли это сделать без блока if / else.

Ответ №1:

С этим связаны две проблемы.

Во-первых, вы можете использовать параметризованные запросы. Посмотрите на PDO, это вам очень поможет. Это не только быстрее для нескольких вставок, но вам не нужно так сильно беспокоиться о внедрении SQL.

Во-вторых, вы можете использовать MySQL ON DUPLICATE KEY UPDATE , чтобы решить эту проблему за вас. В противном случае, когда ваш запрос завершается неудачей, вы не знаете, почему это не удалось. Возможно, это вообще не было проблемой с дублирующимся ключом!

В остальном код с точки зрения or просто отличный.

Комментарии:

1. Итак, будет ли мой дублирующий ключ тем fname / lname, который я проверяю?

2. Нет, дублирующий ключ — это любой ключ в таблице, который завершается ошибкой. Если у вас есть УНИКАЛЬНЫЙ ключ, установленный для fname, тогда да.

Ответ №2:

Вы можете связать столько логических операторов, сколько захотите.

Вы также должны принять во внимание механизмы mysql «при дублировании ключа».

Ответ №3:

Это допустимо? ДА. Рекомендуется ли это? Нет.

Проблема с die() вводом из неудачного SQL-запроса заключается в том, что пользователь в конечном итоге видит ужасный экран, на котором потенциально нет ничего, кроме небольшого количества текста. Это очень плохо.

Читайте также:  Java compareto with null

Вместо этого вы должны обрабатывать эти ошибки таким образом, чтобы вы могли передать пользователю сообщение о неудаче завершения:

 $update_result = $db->query($update); if(!$update_result) < // Yikes! Tell the user something went wrong! // Show them an error page or error message > $insert_result = db->query($insert); if(!$insert_result) < // Yikes! Tell the user something went wrong! // Show them an error page or error message > 

На самом деле, также рекомендуется заглянуть в set_error_handler, который позволяет фиксировать фатальные ошибки PHP и вместо отображения ужасных ошибок, которые потенциально раскрывают ваш php path, вот так:

Неустранимая ошибка: не удается использовать операторы assign-op с перегруженными объектами или смещения строк в / check / out/my/directory /structure/wp-admin/includes/file.php в строке 688

Вы можете отправить их на страницу общей ошибки, которая выглядит намного более профессионально.

Ответ №4:

Возможно, вы захотите изучить синтаксис mysql replace into

Источник

MySQL Insert

When data is put into a MySQL table it is referred to as inserting data. When inserting data it is important to remember the exact names and types of the table’s columns. If you try to place a 500 word essay into a column that only accepts integers of size three, you will end up with a nasty error!

Inserting Data Into Your Table

Now that you have created your table, let’s put some data into that puppy! Here is the PHP/MySQL code for inserting data into the «example» table we created in the previous lesson.

PHP & MySQL Code:

Display:

This code is much simpler to understand than the create table code, as will be most of the MySQL queries you will learn in the rest of this tutorial. Once again, we will cover the code line by line.

‘mysql_query(«INSERT INTO example’

Again we are using the mysql_query function. «INSERT INTO» means that data is going to be put into a table. The name of the table we specified to insert data into was «example».

‘(name, age) VALUES(‘Timmy Mellowman’, ’23’ ) «)’

«(name, age)» are the two columns we want to add data into. «VALUES» means that what follows is the data to be put into the columns that we just specified. Here we enter the name Timmy Mellowman for «name», and 23 for «age».

Be sure to note the location and number of apostrophes and parentheses in the PHP code, as this is where a lot of beginner PHP/MySQL programmers run into problems.

Review & Homework

If all goes as well, this .php page will add a three people to the «example» table every time it is run. Be sure to use your MySQL administration program provided by your web host to ensure that the data was inserted into your table correctly.

Читайте также:  Где хранить файлы python

Be careful not to run this script more than once, otherwise you will be inserting the same people, multiple times. This is called inserting duplicate records and is usually avoided.

Download Tizag.com’s MySQL Book

If you would rather download the PDF of this tutorial, check out our MySQL eBook from the Tizag.com store. You may also be interested in getting the PHP eBook

Found Something Wrong in this Lesson?

Report a Bug or Comment on This Lesson — Your input is what keeps Tizag improving with time!

Источник

MySQL Insert

MySQL Insert is a process of inserting information into a MySQL table. To do so, you have to first create the respective table. It must have column(s) of the same type as that of the content you’d like to insert. Thus, you can’t insert a 300-word article in a column which accepts only integers.

How to Add Data in a MySQL table

The MySQL Insert process can be carried out in several ways: through a direct command from the command line of the MySQL console, via the web-based graphic interface PHPMyAdmin, and by using a PHP script (inserting data and scripts written in other languages — Perl, Python, etc., is possible as well). All MySQL insert methods are characterized with the following elements:

  1. A connection with the MySQL server is established;
  2. A connection with the MySQL Database is established with administrator rights enabled;
  3. A MySQL query is executed, which shows what data is to be inserted in which columns and in which table.

Now let’s for example insert a name and a phone in a phonebook table using the SQL command line:

Insert data in MySQL using the SQL command line

As described above, we need to accomplish three steps to insert new data in a MySQL table. First, let’s log into the MySQl server. To do so, we need to establish an SSH connection to the MySQL server and to log in using the following command:

An example of how to log in to a MySQL server

You need to replace db_user and db_passwd with your username and password settings. Also, you can use a single line to connect to both the MySQL server and the database. Here is the example:

An example of how to log in to a MySQL database

Again you need to replace db_user, db_passwd and db_name with your username, password and database name

Читайте также:  Набор в команду php

Now we need to run a MySQL query to insert the new data in the corresponding columns. You can see the syntax of the query above:

An example of MySQL Insert query’s syntax:

Now let’s see the INSERT statement in action with a real, practical example

An example of how to INSERT data in a MySQL table:

INSERT INTO phonebook(phone, firstname, lastname, address) VALUES(‘+1 123 456 7890’, ‘John’, ‘Doe’, ‘North America’)

This query will insert the phone, name and address data from the values section into the corresponding columns of the phonebook MySQL table.

Insert data using our Control Panel-inbuilt PHPMyAdmin tool

To facilitate its clients to the maximum, NTC Hosting offers a MySQL hosting service, which comes with a control panel-integrated MySQL Database manager via which all our clients can automatically log in their MySQL databases and insert the respective information or import a MySQL dump file using the popular PHPMyAdmin interface. To see how easy it is to insert data in MySQL using our Control Panel and PHPMyAdmin, please check the video below:

An example of how to insert data using PHPMyAdmin (video)

Insert data in MySQL using a PHP script

PHP is a server-side scripting language, which enables the developers to create dynamic web pages, insert PHP code in an HTML code, and easily connect their PHP-based web applications to a MySQL database. Both PHP and MySQL are open-source projects, which makes them widely used as a base for other applications with an open license. Also, both projects are a part of the most commonly used web hosting platform — LAMP (Linux-Apache-MySQL-PHP).

To insert data using a PHP script we need to use the following code

An example of how to connect a PHP script to a MySQL Database


// Connects to your Database
mysql_connect(«mysql.hostname.com», «db_user», «db_passwd») or die(mysql_error());
mysql_select_db(«db_name») or die(mysql_error());
?>

The code in the example above will connect your script to a MySQL server (mysql.hostname.com) using the login credentials of user ‘db_user’. Then it will select the database (db_name). Once connected to the database, let’s try to insert some information in the MySQL table:

An example of how to INSERT data in a MySQL Table using PHP


// Connects to your Database
mysql_connect(«mysql.hostname.com», «db_user», «db_passwd») or die(mysql_error());
mysql_select_db(«db_name») or die(mysql_error());
mysql_query(«INSERT INTO phonebook(phone, firstname, lastname, address) VALUES(‘+1 123 456 7890’, ‘John’, ‘Doe’, ‘North America’)«);
Print «Your table has been populated»;
?>

Источник

Оцените статью