简体   繁体   中英

How to get single value from database with 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.

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.

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.

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];
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM