Php mysqli include function

mythusiva / fix_mysql.inc.php

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

/**
* replacement for all mysql functions
*/
if (!function_exists(» mysql_connect «))
/* warning: fatal error «cannot redeclare» if a function was disabled in php.ini with disable_functions:
disable_functions =mysql_connect,mysql_pconnect,mysql_select_db,mysql_ping,mysql_query,mysql_fetch_assoc,mysql_num_rows,mysql_fetch_array,mysql_error,mysql_insert_id,mysql_close,mysql_real_escape_string,mysql_data_seek,mysql_result
*/
function mysql_connect ( $ host , $ username , $ password )
global $ dbconnect ;
$ dbconnect = mysqli_connect( $ host , $ username , $ password );
return $ dbconnect ;
>
function mysql_pconnect ( $ host , $ username , $ password )
global $ dbconnect ;
$ dbconnect = mysqli_connect(» p: «. $ host , $ username , $ password );
return $ dbconnect ;
>
function mysql_select_db ( $ db , $ dbconnect )
return mysqli_select_db ( $ dbconnect , $ db );
>
function mysql_ping ( $ dbconnect )
return mysqli_ping ( $ dbconnect );
>
function mysql_query ( $ stmt )
global $ dbconnect ;
return mysqli_query ( $ dbconnect , $ stmt );
>
function mysql_fetch_assoc ( $ erg )
return mysqli_fetch_assoc ( $ erg );
>
function mysql_num_rows ( $ e )
return mysqli_num_rows ( $ e );
>
function mysql_affected_rows ( $ e = NULL )
return mysqli_affected_rows ( $ e );
>
function mysql_fetch_array ( $ e )
return mysqli_fetch_array ( $ e );
>
function mysql_error ()
global $ dbconnect ;
return mysqli_error ( $ dbconnect );
>
function mysql_insert_id ( $ cnx )
return mysqli_insert_id ( $ cnx );
>
function mysql_close ()
return true ;
>
function mysql_real_escape_string ( $ s )
global $ dbconnect ;
return mysqli_real_escape_string( $ dbconnect , $ s );
>
function mysql_data_seek ( $ re , $ row )
return mysqli_data_seek( $ re , $ row );
>
function mysql_result ( $ res , $ row = 0 , $ col = 0 )
$ numrows = mysqli_num_rows( $ res );
if ( $ numrows && $ row = 0 )
mysqli_data_seek( $ res , $ row );
$ resrow = (is_numeric( $ col )) ? mysqli_fetch_row( $ res ) : mysqli_fetch_assoc( $ res );
if (isset( $ resrow [ $ col ]))
return $ resrow [ $ col ];
>
>
return false ;
>
function mysql_get_server_info ()
global $ dbconnect ;
return mysqli_get_server_info( $ dbconnect );
>
function mysql_set_charset ( $ csname )
global $ dbconnect ;
return mysqli_set_charset( $ dbconnect , $ csname );
>
function mysql_fetch_object ( $ result )
return mysqli_fetch_object( $ result );
>
>

Источник

Include and Require

Once you have created a script or an HTML content that you want to use in multiple pages is best stored in an external file and included in each page you want to use it. This is accomplished with the include and require functions.
PHP has four commands that can be used to include code from an external file:

  • include() — generates a warning if the external file is missing, but the script will continue execution
  • include_once() — prevent the same file from being included more than once in a page. If the external file is missing, generates a warning and attempts to continue processing the script.
  • require() — If the external file is missing, generates a fatal error, and the script will stop.
  • require_once() — prevent the same file from being inserted more than once in a page. If the external file is missing, stops processing the script and throws a fatal error.

The file path can be either absolute or relative to the current document.
— An absolute path says where a file is starting from the root directory of the computer.

— A relative path uses the position of the current script file as the starting point. To move back one folder, use two periods together followed by a slash (../).

For example, if you have a standard header and menu files (in a » templ » directory located in the curent folder), called » header.php » and » menu.php «, that should be used on all pages. To include these files in a PHP script, use the include() (or require() ) function:

With this method you can insert the same header and menu code in any PHP files in the Web site, all pages in the Web site can include the code of the header and menu files, and if you need to update the header or the menu later, you will only need to make changes in the «header.php» or «menu.php» file.

Using parentheses with the include commands is optional, the following would also work:
include ‘includes/file.php’;
include ‘/usr/MAMP/htdocs/includes/file.php’;

When using a relative file path, you can use use «./» to indicate that the path begins in the current folder. Example:
include(‘./includes/file.php’);

Источник

rubo77 / fix_mysql.inc.php.md

Be aware, that this is just a workaround to fix-up some old code and the resulting project will be more vulnerable than if you use the recommended newer mysqli-functions instead. So only If you are sure that this is not setting your server at risk, you can fix your old code by adding this line at the beginning of your old code:

I am using a framework with php7.0 for the first time and was wondering why it kept on telling me that the mysql_pconnect function is unavailable.

Please how do i use this file?

Wanted to leave another big thanks .

Greatly appreciate the effort here.

In the process of porting a legacy application to modern PHP, I found a few more functions missing that you may wish to add. Here is how I’ve implemented them.

function mysql_escape_string($s) < global $dbconnect; return mysqli_real_escape_string($dbconnect,$s); > function mysql_fetch_row($e) < return mysqli_fetch_row ($e); > function mysql_errno($db) < return mysqli_errno ($db); > function mysql_fetch_object($erg) < return mysqli_fetch_object ($erg); > function mysql_field_name($result,$i) < return mysqli_fetch_field_direct($result,$i); > function mysql_free_result($result) < return mysqli_free_result($result); >

Note:
mysql_affected_rows() does still not work like this if you call mysql_affected_rows() without argument!

Источник

Взаимодействие PHP и MySQL

В этом разделе приводятся описания наиболее часто используемых функций, позволяющих работать с MySQL средствами PHP.

SQL может применятся в прикладных программах двумя способами: в виде встроенного SQL и интерфейса программирования приложений (Application Program Interface, API). Первый способ напоминает использование PHP — инструкции SQL размещаются среди кода прикладной программы. В настоящий момент такой стиль не поддерживает ни MySQL ни PHP. Второй подход заключается в том, что программа взаимодействует с СУБД посредством совокупности функций. Именно такой подход используется при взаимодействии PHP и MySQL.

mysql_connect

resource mysql_connect ([string server [, string username [, string password]]])

Эта функция устанавливает соединение с сервером server MySQL и возвращает дескриптор соединения с базой данных, по которому все другие функции, принимающие этот дескриптор в качестве аргумента, будут однозначно определять выбранную базу данных. Вторым и третьим аргументами этой функции являются имя пользователя username и его пароль password соответственно:

 $dbuser = "root" $dbpasswd = "" $dbcnx = @mysql_connect " 

Переменные $dblocation , $dbuser и $dbpasswd хранят имя сервера, имя пользователя и пароль, и, как правило, прописываются в отдельном файле (к примеру, config.php), который потом вставляется в каждый PHP-файл, в котором имеется код для работы с MySQL:

$dblocation = «localhost»

mysql_close

bool mysql_close ([resource link_identifier])

Эта функция разрывает соединение с сервером MySQL, и возвращает true при успешном выполнении операции и false в противном случае. Функция принимает в качестве аргумента дескриптор соединения с базой данных, возвращаемый функцией mysql_connect .

$dbcnx = @mysql_connect » exit

mysql_select_db

bool mysql_select_db (string database_name [, resource link_identifier])

Использование этой функции эквивалентно вызову команды USE в SQL-запросе, т. е. функция mysql_select_db выбирает базу данных для дальнейшей работы, и все последующие SQL-запросы применяются к выбранной базе данных. Функция принимает в качестве аргументов название выбираемой базы данных database_name и дескриптор соединения resource. Функция возвращает true при успешном выполнении операции и false в противном случае. К примеру:

 $dbcnxВ настоящий момент база данных не доступна, поэтому корректное отображение страницы невозможно.

"

Имеет смысл помещать функции для соединения и выбора базы данных в тот же файл (config.php), где объявлены переменные с именами сервера, пользователя и паролем:

В настоящий момент сервер базы данных не доступен, поэтому корректное отображение страницы невозможно.

» $dbcnxВ настоящий момент база данных не доступна, поэтому корректное отображение страницы невозможно.

»

mysql_query

resource mysql_query (string query)

Эта функция применяется для отправки серверу SQL-запросов. Функция возвращает дескриптор запроса в случае успеха и false в случае неудачного выполнения запроса. В листинге 13.32 показан код, с помощью которого извлекается одна строка из таблицы authors базы данных forum .

$author = mysql_fetch_arrayимя = ".$author['name']."
"$author['passw']."
"$author['email']."
"$author['url']."
"$author['icq']."
"$author['about']."
"$author['photo']."
"$author['time']; Error: ".mysql_error

Результат выполнения показан на следующем рисунке:

mysql_fetch_array

array mysql_fetch_array (resource result)

Эта функция возвращает значения полей в виде ассоциативного массива, в качестве аргумента принимает дескриптор запроса возвращаемый функцией mysql_query . Вот как с помощью этой функции можно вывести все строки таблицы authors :

  "имяпарольe-mailurl"  ".$author['name']." ".$author['passw']."   ".$author['email']." ". $author['url']." ""Error: ".mysql_error 

Результат показан на следующем рисунке:

mysql_result

mixed mysql_result (resource result, int row)

С помощью этой функции можно получить доступ к отдельному полю записи. Допустим, нам нужно вывести имя автора, который первым найдется в базе данных. Сделать это можно следующим образом:

mysql_fetch_object

object mysql_fetch_object (resource result)

Эта функция возвращает поля записи данных в виде объекта. Ниже приведен пример, в котором с помощью этой функции из таблицы authors выводятся имя, URL и e-mail авторов.

name: ".$row->name."

"url: ".$row->url.""email: ".$row->email.""Error: ".mysql_error

Результат выполнения показан на следующем рисунке:

mysql_fetch_row

array mysql_fetch_row (resource result)

В отличие от функции mysql_fetch_object , эта функция возвращает не объект, а массив, в котором содержатся значения полей:

name: «.$row[1].»

«url: «.$row[4].»

«email: «.$row[3].»

«Error: «.mysql_error

Результат выполнения этого кода в точности совпадает с приведённым выше.

Если Вам нужна частная профессиональная консультация от авторов многих книг Кузнецова М.В. и Симдянова И.В., добро пожаловать в наш Консультационный Центр SoftTime.

Источник

Читайте также:  Html code button links
Оцените статью