PHP/MYSQL: Unsure why variable does not contain a value - php

Can someone please explain why this code is not outputting a value for $consultant
When the data base is as follows:
And below is the code...
<?php include ("include/config.php");
$SUC = mysql_query("
SELECT `decisionValue` FROM `teamdecision` WHERE `decisionType` = 'SUconsultant'
")or die($SUC."<br/><br/>".mysql_error());
$SUNumR = mysql_num_rows($SUC);
$consultant = array();
$i="0";
while ($i<$SUNumR && $row = mysql_fetch_assoc($SUC))
{
$consultant[$i] = $row['SUconsultant'];
echo $consultant[$i];
$i++;
}
?>
Thanks

Shouldn't it be $consultant[$i] = $row['decisionValue'];?

In addition to other answers, The $i counter in your script is completely unnecessary. Here's a much simpler approach:
<?php
include('include/config.php');
$SUC = mysql_query("SELECT decisionValue FROM teamdecision WHERE decisionType = 'SUconsultant'") or die(mysql_error());
$consultant = array();
while ($row = mysql_fetch_assoc($SUC))
{
echo $consultant[] = $row['decisionValue'];
}
?>

You're not selecting SUconsultant as one of your columns, so why are you expecting it to be in the result row?
SELECT `decisionValue` FROM `teamdecision`
Whatever key you're referencing in your result set, you should select it as well.

You are only selecting decisionValue in your SQL query, change it to:
SELECT `decisionValue`, `SUconsultant` FROM `teamdecision` WHERE `decisionType` = 'SUconsultant'

Related

Program to fetch a set of rows in PHP has the same code structure, but no results on the other one

Good day. So I have a program that will fetch a set of rows from MySql depending on the select option that I clicked in a select option in HTML and display it into a container in HTML. The code works on the first one, but somehow on the 2nd one it does not fetch the rows I requested. I already checked if the column names are correct and if the value for the select option matches the "if statement" in my PHP code.
In the first snippet of codes, it works properly,
if($_POST["FilterDoc"]=="document_type")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY document_type ASC");
$data = "";
while($rows = mysqli_fetch_assoc($result)){
$document_type = $rows['document_type'];
$date_received = $rows['date_received'];
$application_no = $rows['application_no'];
$hei = $rows['hei'];
$school_name = $rows['school_name'];
$from_co = $rows['from_co'];
$other_govt = $rows['other_govt'];
$contact_person = $rows['contact_person'];
$comment = $rows['comment'];
$program = $rows['program'];
$year_level = $rows['year_level'];
$academic_year = $rows['academic_year'];
$transaction_no = $rows['transaction_no'];
$output = "<table><tr><td>$document_type</td><td>$date_received</td><td>$application_no</td><td>$hei</td><td>$school_name</td><td>$from_co</td><td>$other_govt</td><td>$contact_person</td><td>$comment</td><td>$program</td><td>$year_level</td><td>$academic_year</td><td>$transaction_no</td></tr></table><br>";
$data .= ''.$output.'';
}
echo $data ;
}
But on the 2nd code even though it has the same code structure, doesn't work as I'd hoped to be,
else if($_POST["FilterDoc"]=="other")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY other_govt ASC");
while($data = mysql_fetch_assoc($result))
$data = "";
while($rows = mysqli_fetch_assoc($result)){
$document_type = $rows['document_type'];
$date_received = $rows['date_received'];
$application_no = $rows['application_no'];
$hei = $rows['hei'];
$school_name = $rows['school_name'];
$from_co = $rows['from_co'];
$other_govt = $rows['other_govt'];
$contact_person = $rows['contact_person'];
$comment = $rows['comment'];
$program = $rows['program'];
$year_level = $rows['year_level'];
$academic_year = $rows['academic_year'];
$transaction_no = $rows['transaction_no'];
$output = "<table><tr><td>$other_govt</td><td>$document_type</td><td>$date_received</td><td>$application_no </td><td>$hei</td><td>$school_name</td><td>$from_co</td><td>$contact_person</td><td>$comment</td><td>$program</td><td>$year_level</td><td>$academic_year</td><td>$transaction_no</td></tr></table><br>";
$data .= ''.$output.'';
}
echo $data;
}
Here's the HTML code for my select option,
<select name = "FilterDoc" onchange = "filterby(this);">
<option selected disabled>Filter By</option>
<option value="document_type">Document Type</option>
<option value="date">Date</option>
<option value="hei">HEI</option>
<option value="other">Other Govt.</option>
<option value="person">Person</option></select>
The column name from my database which is other_govt isn't the primary key and has duplicate values. I would really appreciate your help. Thank you!
Run the query SELECT * FROM records ORDER BY other_govt ASC from the MySQL CLI or PHPMyAdmin to make sure it works. Check the error codes from mysqli_query().
This loop is removing all of your result rows silently:
while($data = mysql_fetch_assoc($result))
$data = "";
So that's an error.
You may find it easier to use the extract() function to pull all of the $row values into local variables. Or use mysqli_fetch_ojbect($result) and then use ...<td>{$rows->document}</td>... to generate the output.
Also usually a good idea to escape strings you output to HTML with htmlspecialchars(). Assuming associative array:
Your code will generate a table for every row, probably not want you want. Put the <table> tags outside of the loop, the <tr> inside the loop for each row, then you can iterate over the column values:
foreach ($rows as $col => $val) {
$output .= '<td>'.htmlspecialchars($val).'</td>';
}
You can get the columns in the desired order for the table by specifying them in the SELECT instead of using SELECT *.
All your functional codes are looking fine. But, You have called
while($data = mysql_fetch_assoc($result)) in the second code.
I think mysql_fetch_assoc can't be called twice.
Remove that unwanted line and check it.
You have an extra line of code just right after your query:
while($data = mysql_fetch_assoc($result))
Try the following
$mQuery = "";
$Filter = $_POST["FilterDoc"];switch ($Filter) {
case "document_type":
$mQuery = "your query for document type";
break; case "other":
$mQuery = "your query for other type";
break; } if (!empty($mQuery)) { {
$result = mysqli_query($conn, $mQuery);
$data = "";
while ($rows = mysqli_fetch_assoc($result)) {
$document_type = $rows['document_type'];
$date_received = $rows['date_received'];
$application_no = $rows['application_no'];
$hei = $rows['hei'];
$school_name = $rows['school_name'];
$from_co = $rows['from_co'];
$other_govt = $rows['other_govt'];
$contact_person = $rows['contact_person'];
$comment = $rows['comment'];
$program = $rows['program'];
$year_level = $rows['year_level'];
$academic_year = $rows['academic_year'];
$transaction_no = $rows['transaction_no'];
$output = "<table><tr><td>$document_type</td><td>$date_received</td><td>$application_no</td><td>$hei</td><td>$school_name</td><td>$from_co</td><td>$other_govt</td><td>$contact_person</td><td>$comment</td><td>$program</td><td>$year_level</td><td>$academic_year</td><td>$transaction_no</td></tr></table><br />";
$data.= '<a href = "editdoc.php?v=' . $transaction_no . '" name="documents">' . $output . '</a>';
}
echo $data;
}
else {
echo "Unknown Filter Request";
}

How can I get this php to return the entire column of an sql db

I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}

MSSQL returns multiple rows into array, explode into one array per row

I have an MSSQL query where it SELECTS all rows that meet a specific criteria. In PHP I want to fetch that array, but then I want to convert it into one array per row. So if my query returns 3 rows, I want to have 3 unique arrays that I can work with.
I'm not sure how to go about this. Any help would be greatly appreciated!
Thanks, Nathan
EDIT:
$query = "SELECT * FROM applicants WHERE applicants.user_id ='{$_SESSION['user_id']}'";
$query_select = mssql_query($query , $connection);
if (mssql_num_rows($query_select) == 2){
$message = '2 students created successfully';
}
$i = 0;
while($row = mssql_fetch_array($query_select)) {
$student.$i['child_fname'][$i] = $row['child_fname'];
$student.$i['child_lname'][$i] = $row['child_lname'];
$i++;
}
$query_array1 = $student0;
$query_array2 = $student1;
You will notice from the code above that I am expecting two rows to be returned. Now, I want to take those two rows and create two arrays from the results. I tried using the solution that was give below. Perhaps my syntax is incorrect or I didn't understand how to properly implement his solution. But any help would be greatly appreciated.
$query = mssql_query('SELECT * FROM mytable');
$result = array();
if (mssql_num_rows($query)) {
while ($row = mssql_fetch_assoc($query)) {
$result[] = $row;
}
}
mssql_free_result($query);
Now you can work with array like you want:
print_r($result[0]); //first row
print_r($result[1]); //second row
...
$i=0;
while( $row = mysql_fetch_array(query){
$field1['Namefield1'][$i] = $row['Namefield1'];
$field2['Namefield2'][$i] = $row['Namefield2'];
$field3['Namefield3'][$i] = $row['Namefield3'];
$i++;
}
or if you preffer an bidimensional array:
$i=0;
while( $row = mysql_fetch_array(query){
$result['Namefield1'][$i] = $row['Namefield1'];
$result['Namefield2'][$i] = $row['Namefield2'];
$result['Namefield3'][$i] = $row['Namefield3'];
$i++
}

Giving a variable a value of 1 or 0 based on whether another variable appears in query results

I have a query $sqlStr4 that "selects" these fields from a MySQL database:
loginid
username
created
The query $sqlStr4 is limited to 10 rows / results.
I also have the following variable:
$u = $_SESSION['username'];
I would like to assign another variable $topten a value of 1 if $u equals any of the ten username fields returned by the query $sqlStr4, and a value of 0 if it does not.
How can I do this?
Thanks in advance,
John
Use:
<?php
$u = $_SESSION['username'];
$topten = 0;
$result = mysql_query($sqlStr4);
while ($row = mysql_fetch_assoc($result)) {
if ($row['username'] == $u) {
$topten = 1;
break;
}
}
mysql_free_result($result);
?>
If you had pasted the query, we'd be able to provide a fixed version. You can do this multiple ways, but one would be to add a column to your query and use a CASE statement.
select *, CASE WHEN username = '$u' THEN 1 ELSE 0 END as topten
from ...
This is just an example.. obviously to prevent SQL injection you should parameterize it, or use mysql_real_escape_string(), or a stored procedure, etc etc...
EDIT: I see you want the variable to be in PHP... so you would need to loop through the array to check each one. What is the problem you're having?...
$topten = 0;
if ($result) {
while ($record = mysql_fetch_array($result)) {
if ($record['username'] == $u) $topten = 1;
}
}
Could try something like this...
while ($row = mysql_fetch_assoc($sqlStr4))
{
$topten = ($u == $row['username']) ? 1 : 0;
// the rest of your processing code here
}
There may well be better solutions for your situation. Would be easier if you posted some code!

php array selection

I have the following code and want to manually select an array:
<?php
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' ");
while($article= mysql_fetch_array($articleQuery )){
$aid = $article['id'];
$media = $article['media'];
$link = $article['link'];
}
echo $aid[0];
?>
The problem is that its not really selecting/displaying the correct information. What I want is to be able to select the value of the first array.
Thanks in advance.
$firstrow = null;
while($article= mysql_fetch_array($articleQuery)) {
if ($firstrow === null)
$firstrow = $article;
$aid = $article['id'];
$media = $article['media'];
$link = $article['link'];
//manipulate $aid, $media and $link.
}
//manipulate $firstrow
If you only need the first row, limit the query to one result and execute mysql_fetch_array at most once, instead of in a loop.
Or you can do like this:
$array = array();
while($article = mysql_fetch_object($articleQuery )){
$array[] = $article;
}
echo $array[0]->id; // get first id
echo $array[0]->media; // get first media
echo $array[0]->link; // get first link
echo $array[1]->id; // get second id
echo $array[1]->media; // get second media
echo $array[1]->link; // get second link
// and so on.......
if you want $aid to be an array, you should do something like that:
$aid = array();
while($article= mysql_fetch_array($articleQuery )){
$aid[] = $article['id'];
}
The problem is that its not really
selecting/displaying the correct
information. What I want is to be able
to select the value of the first
array.
What you want is propably this:
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' ");
$article= mysql_fetch_array($articleQuery);
echo $article[0];
You have unnecessary loop. You can also add "limit 1" to sql query. Although I'm not sure I understand your goal correctly.
Using mysql_fetch_assoc, will use the field names as the array indexer, so $article['id'] instead of $article[0]. That way if you change the definition of the table by adding new columns, your code won't break!
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' LIMIT 1");
$article= mysql_fetch_assoc($articleQuery);
var_dump($article);
If you really only want the first result:
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' LIMIT 1"); // note LIMIT clause
if( false !== ($article = mysql_fetch_array($articleQuery )))
{
$aid = $article['id'];
$media = $article['media'];
$link = $article['link'];
}
echo $aid;
If you want them all, but indexable:
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' ");
while($article= mysql_fetch_array($articleQuery ))
{
$aid[] = $article['id'];
$media[] = $article['media'];
$link[] = $article['link'];
}
echo $aid[0];
Why not edit your SQL statement to select only one item?
mysql_query("SELECT * FROM articles WHERE topic = 'IT' LIMIT 1");
But the error in your code, is that you're looping over all your selected records, overwriting your variables on each pass. If you want to store all the rows as an array, you should modify your syntax like this:
while($article= mysql_fetch_array($articleQuery )){
$aid[] = $article['id'];
$media[] = $article['media'];
$link[] = $article['link'];
}
...after which you could access the first row with aid[0].
But instead I'd suggest a different structure:
while($article= mysql_fetch_array($articleQuery )){
$articles[]['aid'] = $article['id'];
$articles[]['media'] = $article['media'];
$articles[]['link'] = $article['link'];
}
What that does, is collect all the data into a single data structure, where each record holds all the data related to the article. You would access it like this:
echo $articles[0]['aid'];
echo $articles[0]['media'];
echo $articles[0]['link'];
If this looks like hebrew to you, take a look at the PHP manual section for arrays.

Categories