3

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.

2
  • If this is a new project, look into using the mysqli extension rather than mysql. Commented May 1, 2013 at 16:01
  • Thanks @Pier-LucGendreau. I have noticed that they are deprecating mysql_ functions. I will convert to the mysqli extension. Commented May 3, 2013 at 12:33

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

This also works well but the best way on my opinion, it is the way JW has done it.
0

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

4 Comments

The SELECT * query won't help here - the question was how to get both values as two columns in a single row. Your query will deliver the results in two rows.
waa you can make a foreach statement
sorry, now it works as you want. and as I said try not to use mysql_* functions
@Memolition this works now. Thanks and thanks for the heads up on mysqli.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.