Open Source SMS Voting System with PHP and MySQL (and Twilio)

Screen Shot 2013-05-10 at 1.19.53 PMMaybe you’re giving a presentation and you’d like a quick “text your vote to this number” real-time poll. Maybe you don’t want to pay the commercial services out there and you have access to a php/mysql server. Here, below, below is some code to make your free poll become a reality. It’s based on this other open source text to vote system: https://github.com/rahims/Text-to-Vote and http://www.twilio.com/blog/2011/05/how-to-create-a-simple-sms-voting-system-using-php.html but instead of sqlite, my version uses MySQL:
handle_incoming_sms.php

<?php
	header('Content-type: text/xml');
	echo '<response>';
	$phone_number = $_REQUEST['From'];
	$team_number = (int) $_REQUEST['Body'];

	if ( (strlen($phone_number) >= 10) && ($team_number > 0) )
	{
            $db=mysql_connect("localhost","user","pass");
            mysql_selectdb("database",$db);
            if (!$db)
            {
              echo "Failed to connect to MySQL: " . mysqli_connect_error();
            }
            $phone_number = mysql_real_escape_string($_REQUEST['From']);
            $team_number = mysql_real_escape_string($_REQUEST['Body']);
            $sql="insert into table set phone='".$phone_number."', team='".$team_number."'";
            $result=mysql_query($sql,$db);
            if (!$result)
            {
   	        die('Invalid query: ' . mysql_error());
            }
	}
	else
        {
		$response = 'Sorry, I didn't understand that. Text the team number to vote. For example, texting 1 will vote for Team 1.';
	}

	echo '<sms>'.$response.'</sms>';
	echo '</response>';
?>

cat get_votes.php

<?php
     $db=mysql_connect("localhost","user","pass");
     mysql_selectdb("database",$db);

if (!$db)
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT COUNT(CASE WHEN team = '1' THEN 1 ELSE NULL END) AS team1,
COUNT(CASE WHEN team = '2' THEN 1 ELSE NULL END) AS team2,
COUNT(CASE WHEN team = '3' THEN 1 ELSE NULL END) AS team3
FROM table";
$result=mysql_query($sql,$db);
                if (!$result)
                {
                         die('Invalid query: ' . mysql_error());
                }
$row = mysql_fetch_assoc($result);
$team1= $row['team1'];
$team2= $row['team2'];
$team3= $row['team3'];
$votes=array((int)$team1, (int)$team2, (int)$team3);
	echo json_encode($votes);
?>