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)

Recommended Answers

All 5 Replies

$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?

yes i think thats it.

ill check that and come back to you.

Cheers

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);
?>

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

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
	}
}
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.