Pull values from multiple SQL tables based on result - php

I need help constructing a Query. I think the best way to explain it is to walk through what I need.
First, I need to look in r_agent_cstm to find the ID number based on the username of the person logged in.
//Find Agent ID
$result1 = mysql_query("SELECT id_c FROM r_agent_cstm WHERE portalusername_c = '$username'");
if (!$result1) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$agent_ID = mysql_fetch_row($result1);
echo $agent_ID[0];
echo "<br />";
Then I need to find any related account IDs for that agent_ID.
//Find Related Accounts
$result2 = mysql_query("SELECT r_agent_accounts_1accounts_idb FROM r_agent_accounts_1_c WHERE r_agent_accounts_1r_agent_ida = '$agent_ID[0]'");
if (!$result2) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result2)) { echo $row['r_agent_accounts_1accounts_idb']; }
echo "<br />";
Somehow...for each result in step 2 (above), I need to find more account info for the IDs found. (Note: below I set the variable that should be the account ID from step 2, but I didn't know how to pass it with more than one result, so I set it instead just so I could work through the logic on it and test that this was working so far.
$testaccount = "1ec39bf0-5ce9-ea23-d362-54c979b75b0f"; //this should be the result(s) from the previous query.
//Find Related Accounts
$result3 = mysql_query("SELECT companyname_c,status_c FROM accounts_cstm WHERE id_c = '$testaccount'");
if (!$result3) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result3)) { echo $row['companyname_c']; }
echo "<br />";
I need help piecing these queries together in a efficient way that will echo out companyname_c and status_c in a tabled format for each result (there may be only 1, none, or there may be hundreds of results).

Related

Trouble Getting Data From Row of mySQL to print out -PHP

I'm trying to get the "goals", which I have stored in rows of a MySQL table along with their "user_id", of a certain user to print out as a list. Here is what I have been trying:
$user_id = (int)$session_user_id;
$result = mysql_query("SELECT user_id,goal1 FROM goals WHERE user_id = $user_id");
if (!$result) {
echo 'Could not run query: '.mysql_error();
}
$row = mysql_fetch_row($result);
echo ($row[1]);
echo ($row[2]);
echo ($row[3]);
echo ($row[4]);
echo ($row[5]);
$session_user_id is a global variable that contains the user id of the user logged in.
There are only five goals per user.
Any ideas?
try this
$user_id = (int)$session_user_id;
$result = mysql_query("SELECT user_id,goal1 FROM goals WHERE user_id = $user_id");
if (!$result) {
echo 'Could not run query: '.mysql_error();
}
while ($row = mysql_fetch_assoc($result)){
echo $row['user_id'] ." ".$row['goal1']."<br />";
}
It looks like you need to be iterating through the rows:
while ($row = mysql_fetch_assoc($result)) {
echo $row['goal1'];
}
Also you should use mysql_fetch_assoc, as mysql_fetch_row is going to be deprecated in PHP 5.5.0

Whats wrong with the syntax in my mysql select statement (php, mysql)

I have a table and i'm trying to extract the maximum value of a column called order_num, which has 33 intries of integers 1 through 33. I want the value "33" in this instance as its the highest number.
$userid is an integer derived from a one row table with a field id that I am trying to retrieve
//get the currentUser ID so we know whos deck to ammend
$userIDSQL = "SELECT id FROM currentUser";
$userIdResult = mysqli_query($db, $userIDSQL) or die("SQL Error on fetching user ID: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_assoc($userIdResult)) {
$result_array[] = $row['id'];
}
//the actual user id
$userId = $row['id'];
echo "user id is " . $userId;
Doing a print_r on $userId shows the array to be empty, that's why the code below doesn't work.. :(
...
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId'";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
$result_array[] = $row['MAX(order_num)'];
echo "the result is" . $result_array['order_num'];
echo "the result is" . $row['order_num'];
echo "the result is" . $result_array['MAX(order_num)']; //tried different methods to get the output.
}
The output I get is
the result is the result is the result is
Does anyone know why i'm not able to get the result from the table?
Edit:
Okay, try this:
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
print_r($row);
}
What do you get?
Your first code to get the userId doesn't work because of your usage of the array, change to:
$userId = 0;
while ($row = mysqli_fetch_assoc($userIdResult)) {
$userId = $row['id'];
}
As I've shown below, if you only expect a single row then remove the while loop and just call fetch_assoc a single time.
Given you only want the single row you don't need the while loop:
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId' LIMIT 1";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
if($reOrderDeckResult && mysqli_num_rows($reOrderDeckResult) == 1)
{
$row = mysqli_fetch_assoc($reOrderDeckResult);
echo 'result: ' . $row['order_num'];
}
else
{
echo 'No rows found!!';
}
I also added LIMIT 1 to the query, and a check to see if there are any rows.
You have renamed your MAX(order_num) AS order_num so you should try to get value using order_num only as echo $result_array['order_num']
and in while you should check whether you are getting value or not by placing below code in while loop
echo '<PRE>';
print_r($row);
echo '</PRE>';
This may helps you..,
<?php
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId'";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
//you have to use the alias name not aggregate function title
$result_array[] = $row['order_num'];
echo "the result is" . $result_array['order_num'];
echo "the result is" . $row['order_num'];
//you have to use the alias name not aggregate function title
echo "the result is" . $result_array['order_num']; //tried different methods to get the output.
}

An instructor retrieves the student who are enrolled in the course he/she teaches

I am building a simple website that helps students and instructors in universities.
I am facing a problem about the following query:
An instructor retrieves the students' IDs and names who are enrolled in the course he/she teaches.
I have the following tables, followed by their fields:
Enrollment (CourseCode - StudentID - Grade)
Studnet (ID - Name)
As you can see the only connector between the two tables is the student ID.
The code that I wrote is
<?
session_start();
$COCODE = $_SESSION['GlobalCode'];
$result11 = mysql_query("SELECT * FROM Enrollment WHERE CourseCode = '$COCODE' ") ;
$row11 = mysql_fetch_array($result11);
$StID = $row11['StudentID'];
$result22 = mysql_query("SELECT * FROM Student where StudentID= '$StID' ") ;
echo "<table border cellpadding=3>";
while($row123 = mysql_fetch_array($result22))
{
echo "<tr>";
echo "<td>".$row123['ID']."</td> ";
echo "<td>".$row123['Name']."</td> ";
echo "</tr>";
}
echo "</table>";
?>
What I am trying to do is to retrieve the course code from the Enrollment table and then retrieving the students names through the ID.
The problem is that I got the following message:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
I hope you can help me solving the problem.
Thanks
Have you tried to narrow down which of the queries is causing the problem? That would be your first step. Some other pointers:
you need to check that each SQL query is successful and returning a valid value before using it in the next query... otherwise that query will cause an error.
Try using: mysql_query ($your_query) or die ('Error: '.mysql_error ()); for each query for a more detailed error message. (for debugging only, not for production)
That error usually means there's something wrong with your query, or perhaps you are not connected to your database. If its the first problem, try changing your query to this:
$result11 = mysql_query("SELECT * FROM `Enrollment` WHERE `CourseCode` = '$COCODE' ");
Otherwise, check your database connection.
Finally, I solved it.
I did the following changes:
$result11 = mysql_query("SELECT * FROM Enrollment WHERE CourseCode = '$InstID' ") or die ('Error: '.mysql_error ());
echo "<table border cellpadding=3>";
while($row11 = mysql_fetch_array($result11))
{
$StID = $row11['StudentID'];
$result22 = mysql_query("SELECT * FROM Students where ID = '$StID' ") or die ('Error: '.mysql_error ());
while($row123 = mysql_fetch_array($result22))
{
echo "<tr>";
echo "<td>".$row123['ID']."</td> ";
echo "<td>".$row123['Name']."</td> ";
echo "</tr>";
}
}
echo "</table>";
mysql_close($con);
?>
Thanks

selecting row from mysql if id matches

I want to select a row from mysql which matches a specific id. I want to get the result if the ID matches, if the ID does not exists in the database, it should not do anything.
I run sth like this:
$q = "SELECT * FROM entries where id= '1'";
$result = mysql_query($q) or die(mysql_error());
if($result){
$row = mysql_fetch_array($result) or die(mysql_error());
$name = $row['name'];
}
echo "hello".$name;
If the id '1' exists in the db, it should get the name, otherwise nothing or at least it should give the error, but when i use this, it just display no any content of the page which comes after this code. What I'm doing wrong?
If it does not display any code after this code, this is probably due to an error occuring and your error handling being set so the error is not displayed.
Try searching for the php error log file (normaly php_error.log) that should contain the error that you do not see.
Another thing i would try is adding more echo statements to see where exactly php stops interpreting.
Like this:
$q = "SELECT * FROM entries where id= '1'";
$result = mysql_query($q);
echo '<br />Query is send';
if(!$result) {
die('<br/>MySQL Error: ' . mysql_error());
}
else {
echo '<br />Result is true';
$row = mysql_fetch_array($result);
echo '<br />tryed fetching row';
if ($row === FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
die('<br/>MySQL Error: ' . mysql_error());
}
}
echo '<br />hello: "' . $name . '"';
That might help to get some more information about your problem.
$id = 1;
$sql = "SELECT `name` FROM `entries` WHERE `id` = $id LIMIT 1" //Since the id is probably an integer type on the DB, the single quotes aren't necessary, and sometimes screw it up. I think MySQL possibly thinks it's a string when in quotes.
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result))
{
$row = mysql_fetch_assoc($result) or die(mysql_error());
$name = $row['name'];
echo 'Hello ' . $name;
}
A SELECT query can return 0 rows if the condition you specified doesn't match any rows, and that isn't an error.
You should rather check the result of mysql_num_rows() after sending the query.
Maybe you should add a else statement to your if.
if($result)
....
else
do something
You might even want to do a try catch statement.

Print multiple columns individually

Using the following query:
SELECT title, nid, created FROM node WHERE uid = $account->uid ORDER BY changed DESC
How do I go about printing the title, nid, created separately (in PHP)?
Thanks! (I'm sure this is VERY simple, I'm just not used to PHP yet)
This is a very basic question, try google for tutorials. Here's a c/p from the very first google result about PHP and mysql which shows the technique you're after.
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * 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['name'];
echo " Age: ".$row['age'];
http://www.tizag.com/mysqlTutorial/mysqlquery.php
If you expect only one result:
$query = "SELECT title, nid, created FROM node WHERE uid = '".$account->uid."' ORDER BY changed DESC";
$resource = mysql_query($query) or die (mysql_error());
if(mysql_num_rows($resource)>0)
{
$row = mysql_fetch_array($resource);
echo 'Title: '.$row['title'].'<br />';
echo 'ID: '.$row['nid'].'<br />';
}
else
{
echo 'no record found';
}
Otherwise (i reread the title of the question now, sorry)
while ($row = mysql_fetch_array($resource))
{
echo 'Title: '.$row['title'].'<br />';
echo 'ID: '.$row['nid'].'<br />';
}

Categories