Hello everyone,
I'm writing a simple poll system and wanted a dynamic way to handle virtually unlimited answers to a quuestion. The way I achieved this was by using a text field in MySQL and using delimeters to seperate the data. It looks like this:
Answer 12~Answer 24~Answer 3`8
I wrote functions to handle this data and they all do great, putting the data into a multidimensional array ($array[0][1] would give "2"). Now I needed a way to write a new string for the database and so I constructed a function to do it, but the problem is since ~ is a delimeter, it adds an extra one to the end every time someone votes. Here is my complete script:
<?php
//Connect to MySQL
mysql_connect("","","");
mysql_select_db("");
function parse_answers($answers,$s1,$s2)
{
$answers_ex = explode($s1,$answers);
for($i = 0; $i < count($answers_ex); $i++){
$answers_exa[$i] = explode($s2,$answers_ex[$i]);
}
return $answers_exa;
}
function display_answers($answers,$pollid)
{
for($y = 0; $y < count($answers); $y++){
for($z = 0; $z < count($answers[$y]); $z++){
if($z != 0){
echo " -- ";
}
echo $answers[$y][$z];
}
echo " <a href=\"polls.php?a=2&id=".$pollid."&an=".$y."\">Vote</a><br>";
}
}
function build_answer_str($answers)
{
for($y = 0; $y < count($answers); $y++){
if($y != 0){
$newstr .= "~";
}
for($z = 0; $z < count($answers[$y]); $z++){
if($z != 0){
$newstr .= "`";
}
$newstr .= $answers[$y][$z];
}
}
return $newstr;
}
if(isset($_GET['a'])){ $a = $_GET['a']; } else { $a = 1; }
if($a == 1){
$p = 1;
if(isset($p)){
$chk_poll = mysql_num_rows(mysql_query("select * from polls where id='".$p."'"));
if($chk_poll > 0){
$poll_info = mysql_fetch_assoc(mysql_query("select * from polls where id='".$p."'"));
echo "<b>" . $poll_info['question'] . "</b><br>";
$answers = parse_answers($poll_info['answers'],"~","`");
print_r($answers);
display_answers($answers,$poll_info['id']);
} else {
echo "<center><b>The poll ID specified does not exist.</b></center>";
}
} else {
echo "<center><b>No poll ID is set.</b></center>";
}
} elseif($a == 2){
if(isset($_GET['id']) && isset($_GET['an'])){
$id = stripslashes(strip_tags($_GET['id']));
$an = stripslashes(strip_tags($_GET['an']));
$poll_info = mysql_fetch_assoc(mysql_query("select * from polls where id='".$id."'"));
$answers = parse_answers($poll_info['answers'],"~","`");
$answers[$an][1]++;
$update = build_answer_str($answers);
echo $update;
mysql_query("update polls set answers='".$update."' where id='".$id."'");
echo "<center><b>Vote added. Thanks!</b></center>";
} else {
echo "<center><b>Needed variables are not set.</b></center>";
}
}
?>