i have the following code, where the user selects an item from a selection box and then the database gets queried to find that match. once it finds that match, i want to be able to extract one field from the entire row. How do i do this?? <?php $searchfor = $_POST['system']; $query ="SELECT * FROM systemconfig_specific WHERE $system LIKE '$searchfor'"; $result = @mysql_query($query); if($rows = @mysql_fetch_array($result)) { //looking for code to go here??? } ?> PHP:
while($rows=@mysql_fetch_array($result)){ $onefield=$rows["dbfield"]; } PHP: I think... bit rusty on mysql at the moment!
So you want to extract one field from one row? That being the case, you can do: $row = @mysql_fetch_array($result); $onefield = $row['fieldname']; PHP: Note that no loops are needed, as you're only interested in one row. You'll probably need to do some checking to see if no rows are returned (i.e. the search term wasn't found). For that, look at mysql_num_rows().
Well I'm not too sure that is what he's asking, but that's how I chose to interpret it His post implies one row, but the query looks like it's designed to return multiple rows (he uses LIKE instead of =)...
optimize the query too: $query ="SELECT ONE_FIELD_NAME FROM systemconfig_specific WHERE $system LIKE '$searchfor'";
I agree. If you're only interested in one column, only query for that column. It might not make a major difference in any given circumstance, but it's just good practice. That makes it really explicit what you're doing (when you come back and look at it in 6 months), and it saves wear & tear on your database server when you start doing hefty queries on huge amounts of data. And then the array returned by mysql_fetch_array (or _assoc...I've always preferred that one) only holds one (hmm. What's the technical term for this in PHP?) thing, which makes your life much easier. And that's what computers are for, right?
Hello, And a little question here regarding your original post.. shouldn't $searchfor = $_POST['system']; PHP: be changed at least to $searchfor = addslashes($_POST['system']); PHP: