Jump to content

help querying the database.


vomitbomb

Recommended Posts

The code below can query the database and get a result only as a row and only selects one row, what I want is to be able to search for a particular name in the fname row.

Say there was an entry in fname called John, I'd like to be able to search for it in the row 'fname'.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("example") or die(mysql_error());

$search = "fname";

// Retrieve all the data from the "example" table
$result = mysql_query("SELECT $search FROM example")
or die(mysql_error());  

// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry 

echo "Name: ".$row['fname'];

?>
</body>
</html>

Link to comment
https://forums.phpfreaks.com/topic/105216-help-querying-the-database/
Share on other sites

Assuming you want to search for the name in fname and fname is a column in your database...

 

<?php

//Make your MySQL connection

$search = "fname";

$sql = mysql_query( "SELECT * FROM `example` WHERE fname = '$search'" )
         or die( mysql_error() );

//Make sure you're doing a mysql_fetch_row if you're only getting one row from the Database
$row = $mysql_fetch_row( $sql );

//OR - You probably will be getting more than one entry, many first names are similar.. so... instead we do:
$myResults = mysql_fetch_array( $sql );

//To list results:
print_r( $myResults );

//To print the one result from $row
echo( "Name: " . $row['fname'] );

?>

 

Addendum on beboo002's post. I HIGHLY recommend you DO NOT use his type of code. That will query what is submitted in the form field and can leave your database open to serious SQL injection and hacking.

Assuming you want to search for the name in fname and fname is a column in your database...

 

<?php


//Make sure you're doing a mysql_fetch_row if you're only getting one row from the Database
$row = $mysql_fetch_row( $sql );

//OR - You probably will be getting more than one entry, many first names are similar.. so... instead we do:
$myResults = mysql_fetch_array( $sql );

?>

 

 

I highly recommend you read the manual regarding mysql_fetch_array().

 

All the mysql_fetch_xxx() functions retrieve fields from a single row. The only differences are in the way the data is stored when fetched.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.