0

Hi all,

taking the following function, id like to know how to get a single value out of the array (assuming 1 record is returned). i know my syntax is wrong for the function, im just typing fast.......

function user($id){
//connect DB
SQL = "username, password, name age"  // etc
$un = $row[username]   //
 $array = ($un, $pw, $name, $age);
return $array;
}

$user = user($id);

How do i get just name? (or any single value)

3
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by colweb
0
$array[3]

would return your name variable, just like 2 would return your password, 1 your username . . .

That's what you were asking for. Right?

0

yes i think thats it.

ill check that and come back to you.

Cheers

0

When you use mysql_fetch_array you can use a number for the array elements or the name, like so:

<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or  die("Could not connect: " . mysql_error());
mysql_select_db("mydb");

$result = mysql_query("SELECT * FROM mytable");

// this will give password and name.
while ($row = mysql_fetch_array($result)) {
    echo "<p>".$row[1], $row['name']."</p>";
}

mysql_free_result($result);
?>

Edited by colweb: n/a

0

hi colweb, thats how i currently do stuff, but im trying to shift my style to OO classes and functions so arrays seem to be the way forward

0

hi colweb, thats how i currently do stuff, but im trying to shift my style to OO classes and functions so arrays seem to be the way forward

Oh well, here is the same in OO style, with 2 functions to open the database and do the query:

<?php
require('db.php'); // contains hostname,username,password and database


function open_database() {
	global $hostname,$username,$password,$database,$db;
	$db = new mysqli($hostname, $username, $password, $database);
	if (mysqli_connect_error()) {
		echo "<p>Cann't connect with database.<br/>Error message: ".mysqli_connect_error()."</p>";
		echo "<p>Please contact the database administrator.</p>";
		exit()
	}
}

function do_query($query);
	global $db;
	$result = $db->query($query);
	if ($db->errno) {
		echo "<p>Error message: ".$db->errno."  ".$db->error."</p>";
		echo "<p>Please contact the database administrator.</p>";
		exit()
	}
        return $result;
}

// main php part
open_database();
$result = do_query("SELECT * FROM atable WHERE acondition='".$condition."'");
$num_results = $result->num_rows;

if ($num_rsults == 0) {
	// no result from query
}
else
	for ($i=0; $i < $num_results; $i++) {
		$row = $result->fetch_assoc();
		echo $row[0];		// use a number for the array element
		echo $row['name']	// or the database name
		// rest of the code
	}
}
?>

Edited by colweb: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.