mutiemule
mutiemule

Reputation: 2539

Selecting multiple rows from one table

This is my table structure

id name value
1 questions 50
2 duration 120

Now, i want to display the value according to the name. I am unable to do the sql statement correct. This is what i have done:

$qry = "SELECT * FROM (
SELECT (SELECT value FROM pq_examsettings) as duration,
       (SELECT value FROM pq_examsettings) as questions
 ) ";
$result= mysql_query($qry);
$row = mysql_fetch_array($result);
$duration = $row['duration'];
$questions = $row['questions'];

Somebody help me on how i can do my query such that my $duration and $questions variables display 120 and 50.

Upvotes: 3

Views: 320

Answers (3)

Memolition
Memolition

Reputation: 494

Use mysqli or pdo functions the mysql_* functions are officially deprecated:

$mysqli = new mysqli($dbserver, $dbmanager, $dbpass, $dbname);
if($mysqli->connect_errno) {
    echo "Error connecting to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$query = $mysqli->query("SELECT * FROM pq_examsettings");
if($query->num_rows){
$new_row = array();
while($row = $query->fetch_assoc()){
    foreach($row as $key => $value){
        if($key == 'name'){
            $array_key = $value;
        }
        if($key == 'value'){
            $new_row[$array_key] = $value;
        }
    }
}
$duration = $new_row['duration'];
$questions = $new_row['questions'];
}

Upvotes: 0

tylert
tylert

Reputation: 301

I'm not familiar enough with MySQL to know a simple way to transpose rows to columns and return the results in one select-- looks like JW gave an answer that does that.

Another option would be to just make two database calls:

$qry = "SELECT value FROM PQ_EXAMSETTINGS WHERE NAME = 'duration'";
$result= mysql_query($qry);
$row = mysql_fetch_array($result);
$duration = $row['value'];

$qry = "SELECT value FROM PQ_EXAMSETTINGS WHERE NAME = 'questions'";
$result= mysql_query($qry);
$row = mysql_fetch_array($result);
$questions = $row['value'];

Upvotes: 0

John Woo
John Woo

Reputation: 263723

give this a try,

SELECT  MAX(CASE WHEN name = 'questions' THEN value END) questions,
        MAX(CASE WHEN name = 'duration' THEN value END) duration 
FROM    pq_examsettings

Upvotes: 4

Related Questions