0

I want to get survey questions from MySQL database, where pollid=1 and echo them out.

I have following code:

<?php
include_once 'init/init.funcs.php';
$pollid=$_GET['pollid'];
$result = mysql_query('SELECT kysimus FROM kysimused where survey_id="1"');
$question = mysql_result($result, 0);
echo $pollid;
echo $question;

?>

It works and I see first question from database, where survey_id =1. But when I write:

<?php
include_once 'init/init.funcs.php';
$pollid=$_GET['pollid'];
$result = mysql_query('SELECT kysimus FROM kysimused where survey_id="$pollid"');
$question = mysql_result($result, 0);
echo $pollid;
echo $question;

?>

It says:

Warning: mysql_result() expects parameter 1 to be resource, boolean given in C:\xampp2\htdocs\Praks\answering.php on line 5

In last example I inserted pollid from url and I am sure that variable $pollid got value '1'. Why the second code doesnt work? I have second question too, how could I create an array of all the questions, which have survey_id = $pollid.Thanks in advance.

2
  • 1
    Use double quotes if you want to pass variable into a statement. Double quotes for the statement and single quotes for the variable. Commented Apr 16, 2014 at 14:11
  • 1
    to elaborate on @iamsleepy 's answer, because you used single quotes it's trying to find the VALUE "$pollid" rather than the value contained within the variable. also, use parameter binding, mysqli or pdo, etc Commented Apr 16, 2014 at 14:14

3 Answers 3

2

Single quote strings do not parse variables, change this: $result = mysql_query('SELECT kysimus FROM kysimused where survey_id="$pollid"');

for this: $result = mysql_query('SELECT kysimus FROM kysimused where survey_id="' . $pollid . '"');

Also dont forget to sanitize your input, something like this would be better: $result = mysql_query('SELECT kysimus FROM kysimused where survey_id="' . (int)$pollid . '"');

at least to make sure its an int

Sign up to request clarification or add additional context in comments.

Comments

1

rewrite your query line as follows:

$result = mysql_query("SELECT kysimus FROM kysimused where survey_id='$pollid'");

This is due to the handling of single and double quotes in php.... The way you wrote it is the reason the variable does not get substituted.

Please see also: http://www.php.net/manual/en/language.types.string.php

more detailed: http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

Comments

0

Try replacing this

$result = mysql_query('SELECT kysimus FROM kysimused where survey_id="$pollid"');

with

$result = mysql_query("SELECT kysimus FROM kysimused where survey_id='$pollid' ");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.