- mysql_fetch_row
- Описание
- Список параметров
- Возвращаемые значения
- Примеры
- Примечания
- Смотрите также
- User Contributed Notes 4 notes
- mysql_field_name
- Description
- Parameters
- Return Values
- Examples
- Notes
- See Also
- User Contributed Notes 12 notes
- search $database for $userquery, found match(es) in $myfield:
- PHP MySQL Select Data
- Select Data With MySQLi
- Example (MySQLi Object-oriented)
- Example (MySQLi Procedural)
- Example (MySQLi Object-oriented)
- Select Data With PDO (+ Prepared Statements)
- Example (PDO)
mysql_fetch_row
Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:
Описание
Возвращает массив с числовыми индексами, содержащий данные обработанного ряда, и сдвигает внутренний указатель результата вперёд.
Список параметров
Обрабатываемый результат запроса. Этот результат может быть получен с помощью функции mysql_query() .
Возвращаемые значения
Возвращает массив строк с числовыми индексами, содержащий данные обработанного ряда, или false , если рядов не осталось.
mysql_fetch_row() обрабатывает один ряд результата, на который ссылается переданный указатель. Ряд возвращается в виде массива. Каждая колонка располагается в следующей ячейке массива, начиная с нулевого индекса
Примеры
Пример #1 Получение одного ряда с помощью mysql_fetch_row()
$result = mysql_query ( «SELECT id,email FROM people WHERE » );
if (! $result ) echo ‘Ошибка запроса: ‘ . mysql_error ();
exit;
>
$row = mysql_fetch_row ( $result );
?php
echo $row [ 0 ]; // 42
echo $row [ 1 ]; // email
?>
Примечания
Замечание: Эта функция устанавливает NULL-поля в значение null PHP.
Смотрите также
- mysql_fetch_array() — Обрабатывает ряд результата запроса, возвращая ассоциативный массив, численный массив или оба
- mysql_fetch_assoc() — Возвращает ряд результата запроса в качестве ассоциативного массива
- mysql_fetch_object() — Обрабатывает ряд результата запроса и возвращает объект
- mysql_data_seek() — Перемещает внутренний указатель в результате запроса
- mysql_fetch_lengths() — Возвращает длину каждого поля в результате
- mysql_result() — Возвращает данные результата запроса
User Contributed Notes 4 notes
Maybe worth pointing out that all the fields returned by this (and other?) calls are returned with type string. This had me puzzled for quite some time.
require ‘prhlavicka.php’ ;
pis_hlavicku ( ‘Vypis článků’ );
?php>
require_once ‘db.php’ ;
$kom = new server ();
$sql = $kom -> query ( «SELECT autor,nazev,obsah FROM `Clanky_Sadek`» );
while ( $data = mysql_fetch_row ( $sql )) ECHO ‘
—AUTOR—
‘ . $data [ 0 ]. ‘
__NÁZEV ČLÁNKU__
‘ . $data [ 1 ]. ‘
..OBSAH ČLÁNKU..
‘ . $data [ 2 ]; >
to print an array, simply use print_r(array name)
like this:
$myrow = mysql_fetch_row($result);
echo «
";
print_r($myrow);
echo "
«;
this will output the array in a readable form, with the index, too. Don’t forget the ‘pre’ tags or the output will be on a single line.
$esi = mysql_list_tables ( $db ); $ris = mysql_fetch_row ( $esi );
//example: $db has >= 1 tabs
echo var_dump ( $ris );
//echoes only array(1). solution:
while( $ris = mysql_fetch_row ( $esi )) echo $ris [ 0 ];
/*debug:
$ris=array(«1st_tab»); . $ris=array(«n_tab»);$ris=false;*/
while ( $ris []= mysql_fetch_row ( $esi ));
//debug:$ris=array(array(«1st_tab»), . array(«n_tab»));
echo $ris [ n ][ 0 ]; //echo:»n_tab»
echo $ris [ 0 ][ n ]; //echo:array | null
?>
hope it helps
- MySQL
- mysql_affected_rows
- mysql_client_encoding
- mysql_close
- mysql_connect
- mysql_create_db
- mysql_data_seek
- mysql_db_name
- mysql_db_query
- mysql_drop_db
- mysql_errno
- mysql_error
- mysql_escape_string
- mysql_fetch_array
- mysql_fetch_assoc
- mysql_fetch_field
- mysql_fetch_lengths
- mysql_fetch_object
- mysql_fetch_row
- mysql_field_flags
- mysql_field_len
- mysql_field_name
- mysql_field_seek
- mysql_field_table
- mysql_field_type
- mysql_free_result
- mysql_get_client_info
- mysql_get_host_info
- mysql_get_proto_info
- mysql_get_server_info
- mysql_info
- mysql_insert_id
- mysql_list_dbs
- mysql_list_fields
- mysql_list_processes
- mysql_list_tables
- mysql_num_fields
- mysql_num_rows
- mysql_pconnect
- mysql_ping
- mysql_query
- mysql_real_escape_string
- mysql_result
- mysql_select_db
- mysql_set_charset
- mysql_stat
- mysql_tablename
- mysql_thread_id
- mysql_unbuffered_query
mysql_field_name
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
Description
mysql_field_name() returns the name of the specified field index.
Parameters
The result resource that is being evaluated. This result comes from a call to mysql_query() .
The numerical field offset. The field_offset starts at 0 . If field_offset does not exist, an error of level E_WARNING is also issued.
Return Values
The name of the specified field index on success or false on failure.
Examples
Example #1 mysql_field_name() example
/* The users table consists of three fields:
* user_id
* username
* password.
*/
$link = mysql_connect ( ‘localhost’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) die( ‘Could not connect to MySQL server: ‘ . mysql_error ());
>
$dbname = ‘mydb’ ;
$db_selected = mysql_select_db ( $dbname , $link );
if (! $db_selected ) die( «Could not set $dbname : » . mysql_error ());
>
$res = mysql_query ( ‘select * from users’ , $link );?php
echo mysql_field_name ( $res , 0 ) . «\n» ;
echo mysql_field_name ( $res , 2 );
?>The above example will output:
Notes
Note: Field names returned by this function are case-sensitive.
Note:
For backward compatibility, the following deprecated alias may be used: mysql_fieldname()
See Also
- mysql_field_type() — Get the type of the specified field in a result
- mysql_field_len() — Returns the length of the specified field
User Contributed Notes 12 notes
This function is slightly stupid to be honest, why not just make an array of field names. You could consolidate the two of these functions that way and it makes it a lot easier to list them when your script is dynamic.
function mysql_field_array ( $query )
$field = mysql_num_fields ( $query );
$names [] = mysql_field_name ( $query , $i );
$fields = mysql_field_array ( $query );
echo implode ( ‘, ‘ , $fields [ 3 ] );
// Count them — easy equivelant to ‘mysql_num_fields’
This is another variant of displaying all columns of a query result, but with a simplified while loop.
$query=»select * from user»;
$result=mysql_query($query);
$numfields = mysql_num_fields($result);while ($row = mysql_fetch_row($result)) // Data
< echo '‘.implode($row,’ ‘).» \n»; >
here’s one way to print out a row of
tags from a table
NOTE: i didn’t test this$result = mysql_query(«select * from table»);
post a comment if there’s an error
james, why make so difficult when it’s very simple :\
for ($i=0; $i $var = mysql_field_name($res_gb, $i);
$row_title .= $var;
>The code in the last comment has an obvious mistake in the for loop expression. The correct expression in the for-loop is $x $y>
$result = mysql_query($sql,$conn) or die(mysql_error());
$rowcount=mysql_num_rows($result);
$y=mysql_num_fields($result);
for ($x=0; $x echo = mysql_field_name($result, $x).’
‘;
>/*
By simply calling the searchtable() function
with these variables it will serach the desired
database and procude a table for each field that
there is a match.
*/?
function searchtable($host,$user,$pass,$database,$tablename,$userquery)
$link = mysql_connect($host, $user, $pass) or die(«Could not connect: » . mysql_error());
$db = mysql_select_db($database, $link) or die(mysql_error());
$fields = mysql_list_fields($database, $tablename, $link);
$cols = mysql_num_fields($fields);for ($i = 1; $i < $cols; $i++) $allfields[] = mysql_field_name($fields, $i);
>
foreach ($allfields as $myfield) $result = mysql_query(«SELECT * FROM $tablename WHERE $myfield like ‘%$userquery%’ «);
if (mysql_num_rows($result) > 0) echo «search $database for $userquery, found match(es) in $myfield:
\n»;
echo «\n\t
\n»;
for ($i = 1; $i < $cols; $i++) echo "\t\t if ($myfield == mysql_field_name($fields, $i)) echo " bgcolor=\"orange\"> «;
> else echo «>»;
>
echo mysql_field_name($fields, $i) . «\n»;
>
echo «\t\n»;
$myrow = mysql_fetch_array($result);
do echo «\t\n»;
for ($i = 1; $i < $cols; $i++)echo "\t\t$myrow[$i] \n»;
>
echo «\t\n»;
> while ($myrow = mysql_fetch_array($result));
echo «\n»;
>
>
>simple sql to xml converter works with any sql query and returns the name of the table as the root element «row» as each row element and the names of the columns are your children of row. fully tested.
function sqlToXml ( $host , $user , $pass , $database , $tablename , $query )
$link = mysql_connect ( $host , $user , $pass ) or die( «Could not connect: » . mysql_error ());
$db = mysql_select_db ( $database , $link ) or die( mysql_error ());$result = mysql_query ( $query );
if(! $result )$numOfCols = mysql_num_fields ( $result );
$numOfRows = mysql_num_rows ( $result );$info = mysql_fetch_assoc ( $result );
//send headers
header ( ‘Content-type: text/xml’ );
header ( ‘Pragma: public’ );
header ( ‘Cache-control: private’ );
header ( ‘Expires: -1’ );
$xml = » ;
$xml .= » < < $tablename >>» ;if( $numOfRows > 0 ) <
do <
$xml .= «» ;
» ;
foreach( $info as $column => $value ) <
$xml .= » < < $column >> >» ;
>
$xml .= «
>
while ( $info = mysql_fetch_array ( $result ));
>
$xml .= «<> >» ;mysql_free_result ( $result );
return $xml ;PHP MySQL Select Data
The SELECT statement is used to select data from one or more tables:
or we can use the * character to select ALL columns from a table:
To learn more about SQL, please visit our SQL tutorial.
Select Data With MySQLi
The following example selects the id, firstname and lastname columns from the MyGuests table and displays it on the page:
Example (MySQLi Object-oriented)
$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) die(«Connection failed: » . $conn->connect_error);
>$sql = «SELECT id, firstname, lastname FROM MyGuests»;
$result = $conn->query($sql);if ($result->num_rows > 0) // output data of each row
while($row = $result->fetch_assoc()) echo «id: » . $row[«id»]. » — Name: » . $row[«firstname»]. » » . $row[«lastname»]. «
«;
>
> else echo «0 results»;
>
$conn->close();
?>Code lines to explain from the example above:
First, we set up an SQL query that selects the id, firstname and lastname columns from the MyGuests table. The next line of code runs the query and puts the resulting data into a variable called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an associative array that we can loop through. The while() loop loops through the result set and outputs the data from the id, firstname and lastname columns.
The following example shows the same as the example above, in the MySQLi procedural way:
Example (MySQLi Procedural)
$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) die(«Connection failed: » . mysqli_connect_error());
>$sql = «SELECT id, firstname, lastname FROM MyGuests»;
$result = mysqli_query($conn, $sql);if (mysqli_num_rows($result) > 0) // output data of each row
while($row = mysqli_fetch_assoc($result)) echo «id: » . $row[«id»]. » — Name: » . $row[«firstname»]. » » . $row[«lastname»]. «
«;
>
> else echo «0 results»;
>You can also put the result in an HTML table:
Example (MySQLi Object-oriented)
$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) die(«Connection failed: » . $conn->connect_error);
>$sql = «SELECT id, firstname, lastname FROM MyGuests»;
$result = $conn->query($sql);if ($result->num_rows > 0) echo «
ID Name «;
// output data of each row
while($row = $result->fetch_assoc()) echo ««.$row[«id»].» «.$row[«firstname»].» «.$row[«lastname»].» «;
>
echo ««;
> else echo «0 results»;
>
$conn->close();
?>Select Data With PDO (+ Prepared Statements)
The following example uses prepared statements.
It selects the id, firstname and lastname columns from the MyGuests table and displays it in an HTML table:
Example (PDO)
class TableRows extends RecursiveIteratorIterator <
function __construct($it) <
parent::__construct($it, self::LEAVES_ONLY);
>function current() return «
» . parent::current(). « «;
>$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDBPDO»;try $conn = new PDO(«mysql:host=$servername;dbname=$dbname», $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare(«SELECT id, firstname, lastname FROM MyGuests»);
$stmt->execute();