How to get single value from database with php - php

I am trying to get a single value from database and store it in a variable Here is the structure of my Database
mysql_connect("localhost","root","") or die(mysql_error());;
mysql_select_db("test") or die(mysql_error());
$result = mysql_query('SELECT * FROM names WHERE name = noshair');
while($row = mysql_fetch_array($result));
{
echo $row['course'] . "<p>";
}
When I use the above code it prints all the courses against my name from data base but I want a specific course name to be selected, like there are 5 courses against my name and i just want all of then separately to be saved in separate variable.

Give this query a try:
SELECT DISTINCT name, GROUP_CONCAT(DISTINCT course ORDER BY course) AS courses;
FROM names
WHERE name = noshair
and change your echo statement to this:
echo $row['courses'] . "<p>";
This should output a list of your course like this -> 'java, c#, php, maths' which you could then put in a variable.

Perhaps you should try the query:
SELECT GROUP_CONCAT(course)
FROM names
WHERE name = noshair;
As side notes, you should stop using mysql_ functions (use mysqli_ or some similar interface). And learn to use parameters in your queries.

Why don't you use php foreach statement like these:
foreach ($row['course'] as $key => $value)
{
echo $value;
}
better still you can use the PHP Implode or Explode method to display them separately.

I think you have to excape the matching value for WHERE:
Try this:
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$result = mysql_query("SELECT * FROM `names` WHERE `name` = 'noshair'");
while($row = mysql_fetch_array($result));
{
$courses[] = $row['course'];
}
var_dump( $courses );
The code saves all the contents to an Array.

Use array to save all courses separately.Then the course name will be save in separate indexes of array like $array[0]="math" and $array[1]="english" .Then use the for loop to save each value in separate variables by setting the condition of loop with total number of values in array.Then the courses will be save separately in different variables like $sub1, $sub2 and so on.Try this code
$con=mysql_connect("localhost","root","")
if(!$con)
{
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('test', $con);
if (!$db_selected) {
die ('Can\'t use test : ' . mysql_error());
}
$result = mysql_query('SELECT * FROM names WHERE name = noshair');
while($row = mysql_fetch_array($result));
{
$value=$row['course'] . "<p>";
echo $value;
$array[]=$value;
}
$total=count($array);
for($i=0;$i<$total;$i++)
{
$n=$i+1;
${'sub'.$n} = $array[$i];
}

Related

Assigning PHP Variable to MySQL Array

I know there is a simple answer but I can't seem to put this together. I am successfully pulling an array from a MySQL table in the following code, but I would like to assign individual PHP variables to each item.
<?php
$con = mysql_connect("$hostname","$username","$password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("$database", $con);
$result = mysql_query("SELECT * FROM table WHERE state=1");
while($row = mysql_fetch_array($result))
{
$value=$row['id'];
}
mysql_close($con);
?>
When I run this loop I get the output of the id's as 1,2,3,4,5,6,7. How can I go about assigning individual PHP variables to each of these values?
You can put the variables in an array.
$values[] = $row['id'];
and then reference it as $value[0], $value[1] ...
Also take a look at list which allows you to assign individual variables as if they were an array.

while loop within foreach

I've got a form with questions which gets answered. Then on the following page I'm trying to validate the questions to see if the answer is correct or not because eventually I must work out a percentage for the test.
$tid1 = $_SESSION['tid'];
$departmentid = $_SESSION['deptid'];
$userid = $_SESSION['userid'];
foreach($_POST['question'] as $key => $answer) {
include 'datalogin.php';
mysql_query("INSERT INTO ex_answer (id,class_name,testname,name,percentage,qnr,answer_chosen,points_scored,result)
VALUES ('0','$departmentid','$tid1','$userid','0','$key','$answer[0] $answer[1] $answer[2] $answer[3] $answer[4] $answer[5] $answer[6] $answer[7] $answer[8]','0','0')");
$sql1="SELECT * FROM ex_question WHERE test_name = '$tid1' AND q_nr = '$key'";
$result1=mysql_query($sql1);
while($row1 = mysql_fetch_array($result1)) {
$q_nr=$row1['q_nr'];
echo $q_nr;
}
}
The problem is (I think) that it is not selecting the question number q_nr = '$key' correctly from the table because echo $q_nr gives no output
If you are getting a valid result (Test the sql in your Database client ) then you should just use the following to access it as an associative array:
mysql_fetch_assoc($result1);
instead of the mysql_fetch_array() or use
mysql_fetch_array($result1, MYSQL_ASSOC)
Test what is being returned to you, comment out your while loop and then do:
$row1 = mysql_fetch_array($result1);
print_r($row1);
before you while loop add the following for validation:
if (!$result1) {
die('Could not query:' . mysql_error());
}
Use mysql_fetch_assoc to be able to use column name indexes on returned array.
You can also output the SQL and test it on the DB, that will show that you are getting the expected results

How Can I Limit the Output from a PHP While Loop?

I have a while loop running that is returning values from a MYSQL table. It returns about 90 entries from the query. My hope is to be able to break these 90 values up and display them in groupings of 5. This may sound confusing so let me share some code samples to help clarify:
$con = mysql_connect("host", "username", "password") or die ("Unable to connect to server");
mysql_select_db("database") or die ("Unable to select database");
$sql = mysql_query("SELECT * FROM `table` WHERE column IS NOT NULL AND column <> ''");
Here I am pulling the values out that I need from the table...
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$column=$row['column'];
echo $id . '<br>';
echo $column . '<br>';
}
At this point, I have run the loop and get the display of all 90 entries. How can I pull the values out and display them in smaller chunks? If I use the looped values outside of the while loop, it just gives me the last value from the set. Is there a simple way to use the unique $id value from the column to get a specific grouping within the loop?
This will add more br's and a hr after each 5 records:
$cnt = 0;
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$column=$row['column'];
echo $id . '<br>';
echo $column . '<br>';
if($cnt % 5 == 0) echo "<br><br><hr><br><br>";
$cnt++;
}
Here is one (not very sophisticated) approach you could take:
$group_size = 5;
$tracking_variable = 0;
while ($row = function_to_fetch_row()) {
if ($tracking_variable == 0) {
// logic for the start of a grouping
}
// logic to display the row
$tracking_variable = ($tracking_variable + 1) % $group_size;
if ($tracking_variable == 0) {
// logic for the end of a grouping
}
}
if ($tracking_variable > 0) {
// logic for the end of the final grouping
}
You want to save this data in a variable, and reference it outside of the loop.
Try this:
$data = array();
while($row=mysql_fetch_array($sql))
{
$data[$row['id']] = $row['column'];
}
And now you can just display specific rows:
print $data[$someRow];

Display mysql data in php function

Ok i got a problem now i want to display a data from the database and display it through a function now how do i do that??
like i have fetched a row from the database and its name is $row_field['data']; and it is correct now i have assigned a variable to it like this $data = $row_field['data']; now if i call it in a function it shows undefined variable even after i assigned it global in the function like this
function fun(){
global $data;
echo $data;
}
but if i assign it a value like 1 or 2 or anything it gets displayed without any error why is that so??
If it displays if you assign it a value like 1 or 2 while still in the global scope, then I can only assume that your database did not return the result you thought it did. Does the database value display if you echo it out outside of the function?
Global is evil. I dont know what you are trying to do, but why dont you just do the query in the function itself?
If you have a column named data and your php call was something like
$result = mysql_query("SELECT data FROM mytable");
while ($row_field = mysql_fetch_assoc($result, MYSQL_NUM)) {
...
}
Then you could replace ... with print $row_field['data'].
Else please provide a snippet of your code where you query the db and retrieve the result.
When learning php try to start with simple things. For example in order to get some data from a database follow the examples from php website.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
If all this goes well go a little further change a little the while loop.
$myArray = array();
while ($row = mysql_fetch_assoc($result)) {
$myArray[] = $row;
}
mysql_free_result($result);
// now you can start playing with your data
echo $myArray[0];
Small steps...

How do I loop through a PHP array containing data returned from MySQL?

Ok I have a table with a few fields. One of the fields is username. There are many times where the username is the same, for example:
username: bob
password: bob
report: 1
username: bob
password: bob
report: 2
I did a SQL statement to select * where username='bob'; but when I do the following PHP function, it will only return the last result:
$thisrow = mysql_fetch_row($result);
I need to get every field from every row. How should I go about doing this?
$mainsection="auth"; //The name of the table
$query1="select * from auth where username='$user'";
$result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); //do the query
$thisrow=mysql_fetch_row($result);
echo "Study: " . $thisrow[1] . " - " . $thisrow[5];
Sorry for such a dumb question. I can't seem to get the while loops of more than one field working for the life of me.
mysql_fetch_row fetches each row one at a time. In order to retrieve multiple rows, you would use a while loop like this:
while ($row = mysql_fetch_row($result))
{
// code
}
Use a loop, and use mysql_fetch_array() instead of row:
while($row = mysql_fetch_array($result)) {
echo "Study: " . $row[1] . " - " . $row[5];
// but now with mysql_fetch_array() you can do this instead of the above
// line (substitute userID and username with actual database column names)...
echo "Study: " . $row["userID"] . " - " . $row["username"];
}
I suggest you to read this:
http://www.w3schools.com/php/php_mysql_select.asp
It will give you an overview idea of how to properly connect to mysql, gather data etc
For your question, you should use a loop:
while ($row = mysql_fetch_row($result)){//code}
As said by htw
You can also obtain a count of all rows in a table like this:
$count = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM table"));
$count = $count["count"];
You can also append a normal WHERE clause to the select above and only count rows which match a certain condition (if needed). Then you can use your count for loops:
$data = mysql_query("SELECT * WHERE username='bob'");
for ($i = 0; $i
Also, mysql_fetch_array() is usually a lot easier to use as it stores data in an associative array, so you can access data with the name of the row, rather than it's numeric index.
Edit:
There's some kind of bug or something going on where my second code block isn't showing everything once it's posted. It shows fine on the preview.
I like to separate the DB logic from the display. I generally put my results into an array that I can call within the HTML code. Purely personal preference; but here's how'd I'd approach the problem: (I'd take the $sql out of the error message in production)
<?php
$sql="
SELECT *
FROM auth
WHERE username='$user';
";
$result = mysql_query($sql)
or die("Failed Query : ".mysql_error() . $sql); //do the query
while ($ROW = mysql_fetch_array($result,MYSQL_ASSOC)) {
$USERS[] = $ROW;
}
?>
HTML CODE
<? foreach ($USERS as $USER) { ?>
Study: <?=$USER['dbFieldName'];?> - <?=$USER['dbFieldName2'];?>
<? } //foreach $USER ?>
$qry=mysql_query(select * where username='bob');
if(mysql_num_rows($qry))
{
while($row=mysql_fetch_array($qry,MSQL_NUM))
{
echo $row[0]." ".$row[1]." ".$row[2]."<br>";
}
}

Categories