Print multiple columns individually - php

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 />';
}

Related

Pull values from multiple SQL tables based on result

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).

Grabbing more than just one row from DB

$sql = "SELECT title, article, filename, caption FROM articles
INNER JOIN images WHERE articles.image_id = images.image_id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
var_dump($row);
This only grabs the first row in the db when what I need is for it to grab all rows. How can I achieve this?
fetch_assoc() returns the next row of the result set with each call, so you need to call it in a loop like this:
while($row = $result->fetch_assoc()) {
var_dump($row);
}
The loop ends when $row = null (i.e. there's no more rows in the result set).
Please have a look at the Quick start guide, more specifically the Executing statements chapter. Right from that page:
$mysqli->real_query("SELECT id FROM test ORDER BY id ASC");
$res = $mysqli->use_result();
echo "Result set order...\n";
while ($row = $res->fetch_assoc()) {
echo " id = " . $row['id'] . "\n";
}

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.
}

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.

Pulling data and printing it in an HTML table

From a MySQL table called "submission" containing the fields "loginid, submissionid, title, url, datesubmitted, displayurl", I would like to print an HTML table thats contains all "title" and corresponding "datesubmitted" where "loginid" equals "$profile." The code I am trying to use is below. It isn't working. Any ideas why it isn't working?
Thanks in advance,
John
$profile = $_GET['profile'];
$sqlStr = "SELECT loginid, submissionid, title, url, datesubmitted, displayurl
FROM submission
WHERE loginid = $profile
ORDER BY datesubmitted DESC";
$result = mysql_query($sqlStr);
$arr = array();
echo "<table class=\"samplesrec\">";
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td class="sitename1">'.$row["title"].'</td>';
echo '</tr>';
echo '<tr>';
echo '<td class="sitename2">'.$row["datesubmitted"].'</a></td>';
echo '</tr>';
}
echo "</table>";
Your query is probably failing.
Try echoing the return from mysql_error(); after trying the query to see what the issue might be.
You should also protect your input against injection. If loginID is a username, you need to surround a string in a mySQL query with quotes - if loginID is a username. If it's an integer you may be okay.
There are more robust ways to do this but simply:
$profile = mysql_real_escape_string($_GET['profile']);
$sqlStr = "SELECT loginid, submissionid, title, url, datesubmitted, displayurl
FROM submission
WHERE loginid = '$profile'
ORDER BY datesubmitted DESC";
$result = mysql_query($sqlStr);
if($result) {
// Handle output
}
else {
echo 'query failed';
// don't leave this here in production!
echo mysql_error();
}
One problem I can see is you are not checking in the return value of mysql_query()
mysql_query() returns false if it fails to execute the query. So you need to do a check, something like:
$result = mysql_query($sqlStr);
if(! $result) {
//....error occured...prepare $message
die($message);
}
your question regards to debugging, the most important programming art. Noone can find an error for you, you have to do it yourself. With help of little tricks.
change $profile = $_GET['profile']; to $profile = intval($_GET['profile'];)
change $result = mysql_query($sqlStr); to
$result = mysql_query($sqlStr) or trigger_error(mysql_error()." in ".$sqlStr);
andd following 2 lines at the top of your code, run it again and see what it say. if still nothing, you don't have matching records in your table.
ini_set('display_errors',1);
error_reporting(E_ALL);

Categories