PDA

View Full Version : Variables in a database



dreamerp
March 7th, 2005, 06:21 PM
Hello,
Is it possible to connect to a database, gather variables, and then have another connection to a database using those variables? Is it possible to have variables in the sql query to SELECT information from a database as well as use variables in the database connection? I tried but it didn't work, can someone help?

THanks!

Cybernoid
March 8th, 2005, 02:43 AM
Hello,
Is it possible to connect to a database, gather variables, and then have another connection to a database using those variables? Is it possible to have variables in the sql query to SELECT information from a database as well as use variables in the database connection? I tried but it didn't work, can someone help?

THanks!

I'm not quite sure I understood the question, but using PHP variables in MySQL -commands go like this


SELECT * FROM users WEHRE id=$id

$is being a variable.

When you connect to a database and get a st of values, you can read them into an array like this:



$query="SELECT * FROM users WHERE id=$id";
$result=mysql_query($query);
$array = mysql_fetch_row($result);


Now you have the results of a row in an array and you can use them by


$id=$array[0];

etc.

If you need multiple rows, use for- or while-loops.

bwh2
March 8th, 2005, 02:51 AM
if you want, post your code and we can point out the errors.

lucidsurf
March 9th, 2005, 07:53 AM
Hey there, I get the feeling you want to create a query with an inner loop that runs another query. The inner query would then selects data from the db based on variables from the outer query. If that's correct then, yes, that's possible - I do it all the time. Here's a basic example:


$query = mysql_query ("SELECT * FROM USERS WHERE User_ID='$userID'");

while ($row = mysql_fetch_array($queryGoals,MYSQL_ASSOC)) {

//create a variable
$myUserName = $row{'User_Name'};

//print it to the screen
Echo "My name is: ".$myUserName;

//Inner Query. Note the use of the $myUserName variable in the SQL
$query2 = mysql_query ("SELECT * FROM UserPets WHERE User_Name='$myUserName'");

while ($row2 = mysql_fetch_array($query2,MYSQL_ASSOC)) {

$myPetsName = $row2{'Pets_Name'};

Echo "My name is: ".$myPetsName;

}
}

This demonstrates how a query within a loop can use variables from the outer loop to run sub-queries. Strange example (conceptually it all works) but it's been a strange day.

Good luck :sure: