Return result query php

mysql_result

Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:

Описание

Возвращает содержимое одного поля из набора результата MySQL.

Работая с большими результатами запросов, следует использовать одну из функций, обрабатывающих сразу целый ряд результата (указаны ниже). Так как эти функции возвращают значение нескольких ячеек сразу, они НАМНОГО быстрее mysql_result() . Кроме того, учтите, что указание численного смещения работает намного быстрее, чем указание колонки, или колонки с таблицей через точку.

Список параметров

Обрабатываемый результат запроса. Этот результат может быть получен с помощью функции mysql_query() .

Номер получаемого ряда из результата. Нумерация рядов начинается с 0 .

Имя или смещение получаемого поля.

Может быть как смещением поля, именем поля, так и именем поля вместе с таблицей (таблица.поле). Если для поля был указан псевдоним (‘select foo as bar from. ‘), используйте его вместо имени самого поля. Если не указан, возвращается первое поле.

Возвращаемые значения

Содержимое одного поля из набора результата MySQL в случае успешного выполнения, или false в случае возникновения ошибки.

Примеры

Пример #1 Пример использования mysql_result()

$link = mysql_connect ( ‘localhost’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) die( ‘Ошибка соединения: ‘ . mysql_error ());
>
if (! mysql_select_db ( ‘database_name’ )) die( ‘Ошибка выбора базы данных: ‘ . mysql_error ());
>
$result = mysql_query ( ‘SELECT name FROM work.employee’ );
if (! $result ) die( ‘Ошибка выполнения запроса:’ . mysql_error ());
>
echo mysql_result ( $result , 2 ); // выведет имя третьего сотрудника

Примечания

Замечание:

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

Смотрите также

  • mysql_fetch_row() — Обрабатывает ряд результата запроса и возвращает массив с числовыми индексами
  • mysql_fetch_array() — Обрабатывает ряд результата запроса, возвращая ассоциативный массив, численный массив или оба
  • mysql_fetch_assoc() — Возвращает ряд результата запроса в качестве ассоциативного массива
  • mysql_fetch_object() — Обрабатывает ряд результата запроса и возвращает объект
Читайте также:  Mac os удалить python полностью

Источник

how to return mysql data from a php function

I have a php function that I’m hoping will return all data. The problem right now is it will return the first row called then hang out and I’m not sure why.

 function get_user_info($id,$field='') < //connect to database include_once("../config.php"); $qry= "SELECT `$field` FROM `".$user_table."` WHERE `id` ='$id'"; //die($qry); $result=mysql_query($qry); if($result) < if(mysql_num_rows($result)>0) < //query successful $data=mysql_fetch_row($result); $user_info= $data[0]; >else < $user_info ="invalid field"; >> else < $user_info="invalid data"; >return $user_info; > 

If I run a function like echo (get_user_info($user_id,’username’).» «.get_user_info($user_id,’username’)); It returns username invalid data For the life of me I can’t figure out why it won’t get the data assocated with each row of get_user_data EDIT: It seems to be dying at $result=mysql_query($qry); which returns Incorrect table name » EDIT2: Looks like the problem was that I was only including the config file once and using a variable for my table name which was getting unset when I tried to call it a second time. EDIT 3: Here is the final function

//connect to database if(file_exists('..config.php')) < include_once("../config.php"); >function get_user_info($id,$field) < //get users table global $user_table_name; $qry= "SELECT `$field` FROM `$user_table` WHERE `id` ='$id'"; $result=mysql_query($qry) or die(mysql_error()); if($result) < if(mysql_num_rows($result)>0) < //query successful $data=mysql_fetch_row($result); $user_info= $data[0]; >else < $user_info =$qry; >> else < $user_info="invalid data"; >return $user_info; > 

echo the query, see what he run , and if you have error show them, echo mysql_errno($link) . «: » . mysql_error($link) . «\n»;

you shouldn’t include anything inside of function. And your solution most likely is vulnerable to SQL injection

5 Answers 5

function mysql_fetch_all($res) < while($row=mysql_fetch_array($res)) < $return[] = $row; >return $return; > 
$data = mysql_fetch_all($result); 

@Bandon if u want only selected field then optimize Query( SELECT username,user_id FROM ) not the fetch metho

that’s what I’m trying to do. Just do it in a generic function so I can request just the rows I need.

Well I see now what are you trying to do.

Читайте также:  Css center img in smaller div

First of all, your idea of having such function is absolutely brilliant. Only few people ever come to it.
But implementation seems not that good.

You are trying to create both mysql helper function and specialized function to get particular user data at once. Let me show you how can you make former one and then let’s see if you will need latter one.

Every php developer need a function like yours, but general purpose one — to get a single value from query, without typing tons of repetitive code of sanitizing parameters and and getting data and error control and stuff.
Here is an example of such function, using placeholders to pass data into query. These placeholders of printf family, so, you have to use %s to represent a string and %d to represent int

function dbgetvar() < $args = func_get_args(); $query = array_shift($args); foreach ($args as $key =>$val) < $args[$key] = mysql_real_escape_string($val); >$query = str_replace("%s","'%s'",$query); $query = vsprintf($query, $args); $res = mysql_query($query); if (!$res) < trigger_error("dbgetarr: ".mysql_error()." in ".$query); return FALSE; >else < $row = mysql_fetch_row($res); if (!$row) return NULL; return $row[0]; >> 

Having this function in your config file, you can get your user info this way

$name = dbgetvar("SELECT name FROM users WHERE >and many other things like this
$name = dbgetvar("SELECT id FROM users WHERE name=%s AND surname = %s", $_GET['name'], $_GET['surname']); 

I doubt you will need specialized function for userinfo anymore. However, it can be done too, based on this function

Источник

How to fetch and return query results?

I am creating a function that is suppose to get the first name and last name from the database and return the query. Something is not right about it though. The first and last names don’t show up. I’m not getting any errors or warnings and I’ve tried all of the answers provided on this site and others(there is not much though). Can someone tell me what is wrong with it ?

public function getFirstAndLastName() < $username = $this->user['username']; $query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? "); $query->bind_param("s", $username); $query->execute(); $query_result = $query->get_result(); $query_result->fetch_array(); while ($row = $query_result->fetch_assoc()) < $row['first_name']; >return $row; > 

Hello. You might need to pass the connection variable to your function or list the connection variable as global.

Читайте также:  Применение python для анализа данных

2 Answers 2

First of all if you are trying to finding a better way you can use this one

public function getFirstAndLastName() < $username = $this->user['username']; $query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? "); $query->bind_param("s", $username); $query->execute(); $query_result = $query->get_result(); $result = $query_result->fetch_all(MYSQLI_ASSOC); Return $result; > 

mysqli has a handy function that instantly returns an array from the query result: mysqli_fetch_all(). So instead of this lines

while ($row = $query_result->fetch_assoc())

it could be just a single line:

if you are looking to finding the answer why your function will return null i will explain for you :

There is some mistake in your codes

first of all when you execute this line $query_result->fetch_array();

actually you just make empty the mysqli buffer! so you don’t have anything in buffer to catch it in this line -> while ($row = $query_result->fetch_assoc())

and in other hand even if you had something in buffer then you dont do nothing in this line -> $row[‘first_name’];

if you are looking to correct your codes you should write the code like this -> first of all make comment this line -> $query_result->fetch_array();

public function getFirstAndLastName() < $username = $this->user['username']; $query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? "); $query->bind_param("s", $username); $query->execute(); $query_result = $query->get_result(); //$query_result->fetch_array(); while ($row = $query_result->fetch_assoc()) < $result[] = $row['first_name']; >return $result; > 

if you are looking to get both first name and last name you have to do like this ->

public function getFirstAndLastName() < $username = $this->user['username']; $query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? "); $query->bind_param("s", $username); $query->execute(); $query_result = $query->get_result(); //$query_result->fetch_array(); while ($row = $query_result->fetch_assoc()) < $result[] = $row; >return $result; > 

Источник

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