Solved

How to connect a php voting script together

Posted on 2011-02-28
7
316 Views
Last Modified: 2012-05-11
hey guys so I have two scripts.  One script is the action vote script which when pressed takes all the information from the song.  The second script is supposed to take that information and read it and do a query based on the information.  Im having trouble connecting these two scripts together.

The first script is

if($_REQUEST['action']=="vote"){
// NOTE: Some PHP installations may use a different nomenclature for the "$_REQUEST" such as "$_HTTP_SERVER"
      $theContent = "";
     
      // Here we are extracting all of the info contained in the request.
 for ($i=0; $i<count($_REQUEST['value']);$i++){
       $theContent = urldecode($_REQUEST['value'][$i]);
}

      foreach($_REQUEST as $key => $value){
            $theContent .= $key." : \t".urldecode($value)."\r\n";
      }

      strstr( PHP_OS, "WIN") ? $slash = "\\" : $slash = "/";
     
print "$testFile";

      if(writeTextFile2(getcwd ().$slash.$testFile, $theContent, 'w+')){
            print "&retval=ok";
      } else {
            print "&retval=error";
      }

}

the second script is



$songid = '??????????';



include("connection.php");

//we need to do a select to grab the current votes the song has
$result = mysql_query("SELECT voteup FROM music WHERE song_title = '$songid' ") or die('Query unsuccessful: ' . mysql_error());

while($row = mysql_fetch_array($result))
  {
  $voteCnt =  $row['voteup']; //grab the current vote count
 
  }

$voteCnt++; //add 1 vote to the count


//now we need to insert the new vote total back into the db

$success=mysql_query("UPDATE music SET voteup = '". $voteCnt ."' WHERE song_title ='$songid' ");
if (!$success){
       die(mysql_error());
       echo "fail";  
}else{
      echo "database entry entered";
}
//close your db connection
mysql_close($con);

how do i transmit the information from the firstr script to the second one
0
Comment
Question by:jvsmooth
  • 5
  • 2
7 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 35009635
Please use the code snippet feature when you post code here at EE.  It makes it easier to read and copy, and it gives us line numbers that facilitate conversation.

From the look of that code snippet, I am going to guess that you did not write it yourself.  But in any case, I think you might benefit from getting some foundation in how PHP and MySQL work together.  This book can help with that.
http://www.sitepoint.com/books/phpmysql4/

I will try to cobble together a sample script that shows how to keep counts of votes.  It seems to be a fairly common question and one that is not well understood.
0
 

Author Comment

by:jvsmooth
ID: 35011713
The real question is     is how do I use the information outputted by the first script as individual variables for the second script
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 35013264
Umm... You probably do not want to use either script.  I'll try to have an example for you in a little while.  It requires a couple of data base tables.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 35018560
Here is how I might go about accumulating votes.  

Step one - create two tables.  The EE_vote_colors table is the subject of our survey.  The EE_vote_votes table is where we record the votes.  By keeping a separate table for the votes we are creating a log of all votes that will enable us to answer questions related to trending topics, geographical location of our voters (tied to IP address), etc.  We could probably keep a great deal more interesting information in this table if we had, for example, a requirement for voters to be registered and logged in.
<?php // RAY_temp_jvsmooth_create.php
error_reporting(E_ALL);


// DEMONSTRATE THE VOTING ALGORITHM - CREATE THE TABLES


// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";        // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "??";
$db_word = "??";

// LIVE DATABASE CREDENTIALS
require_once('RAY_live_data.php');


// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-connect.php
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $errmsg <br/>";
    die('NO DATA BASE');
}
// IF WE GOT THIS FAR WE CAN DO QUERIES


// REMOVE OLD VERSIONS OF THE TABLES; IGNORE ANY ERRORS (LIKE NO TABLE OF THIS NAME)
// mysql_query("DROP TABLE EE_vote_colors");
// mysql_query("DROP TABLE EE_vote_votes");


// CREATE THE COLOR TABLE
$sql
= "CREATE TABLE EE_vote_colors
( _key  INT         NOT NULL AUTO_INCREMENT PRIMARY KEY
, color VARCHAR(10) NOT NULL DEFAULT ''
)"
;
$res = mysql_query($sql) or die( "$sql<br/>" . mysql_error() );


// CREATE THE VOTES TABLE
$sql
= "CREATE TABLE EE_vote_votes
( _key       INT         NOT NULL AUTO_INCREMENT PRIMARY KEY
, color      VARCHAR(10) NOT NULL DEFAULT ''
, ip_address VARCHAR(16) NOT NULL DEFAULT 'unknown'
, when_voted TIMESTAMP
)"
;
$res = mysql_query($sql) or die( "$sql<br/>" . mysql_error() );


// LOAD THE STANDARD ROY-G-BIV DATA INTO THE COLOR TABLE
$res = mysql_query( "INSERT INTO EE_vote_colors ( color ) VALUES ( 'Red'    )" );
$res = mysql_query( "INSERT INTO EE_vote_colors ( color ) VALUES ( 'Orange' )" );
$res = mysql_query( "INSERT INTO EE_vote_colors ( color ) VALUES ( 'Yellow' )" );
$res = mysql_query( "INSERT INTO EE_vote_colors ( color ) VALUES ( 'Green'  )" );
$res = mysql_query( "INSERT INTO EE_vote_colors ( color ) VALUES ( 'Blue'   )" );
$res = mysql_query( "INSERT INTO EE_vote_colors ( color ) VALUES ( 'Indigo' )" );
$res = mysql_query( "INSERT INTO EE_vote_colors ( color ) VALUES ( 'Violet' )" );

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 35018639
Step two - use the tables to collect votes.  You can see the script in action here:
http://www.laprbass.com/RAY_temp_jvsmooth_vote.php

After initialization, the first thing we do comes at line 40, where we get an array of the colors.  Starting on line 52 we test to see if any votes have been cast.  If so we get the client IP address and we use the iterator on line 55 to retrieve each of the votes for the colors.  We insert one row into the "votes" table for each vote cast.

Next we show the statistics for all the colors.  The iterator on line 69 runs a set of queries.  We display one line for each color, staring on line 77.

Our action script processing is complete at line 92.  The only thing that remains is to produce the form, and that happens on lines 94 through the end of the script.

HTH, ~Ray
<?php // RAY_temp_jvsmooth_vote.php
error_reporting(E_ALL);


// DEMONSTRATE THE VOTING ALGORITHM


// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";        // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "??";
$db_word = "??";

// LIVE DATABASE CREDENTIALS
require_once('RAY_live_data.php');


// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-connect.php
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $errmsg <br/>";
    die('NO DATA BASE');
}
// IF WE GOT THIS FAR WE CAN DO QUERIES


// GET THE ARRAY OF COLORS FROM THE DATA BASE
$colors = array();
$sql = "SELECT color FROM EE_vote_colors";
$res = mysql_query($sql) or die( "$sql<br/>" . mysql_error() );
while ($row = mysql_fetch_assoc($res))
{
    $colors[] = $row["color"];
}
// ACTIVATE THIS TO SEE THE COLORS
// var_dump($colors);


// IF ANYTHING WAS POSTED
if (!empty($_POST["color_selections"]))
{
    $ipa = (!empty($_SERVER["REMOTE_ADDR"])) ? $_SERVER["REMOTE_ADDR"] : 'unknown';
    foreach($_POST["color_selections"] as $color => $nothing)
    {
        // NORMALIZE THE POST DATA
        $rgb = mysql_real_escape_string(ucfirst(strtolower(trim($color))));

        // SKIP FIELDS THAT ARE NOT PART OF OUR COLOR SET (POSSIBLE ATTACK?)
        if (!in_array($rgb, $colors)) continue;

        // RECORD A VOTE FOR THIS COLOR
        $sql = "INSERT INTO EE_vote_votes ( color, ip_address ) VALUES ( '$rgb', '$ipa' )";
        $res = mysql_query($sql) or die( "$sql<br/>" . mysql_error() );
    }

    // SHOW THE STATS FOR THE COLORS
    foreach ($colors as $color)
    {
        $sql = "SELECT ip_address, when_voted FROM EE_vote_votes WHERE color = '$color' ORDER BY when_voted DESC";
        $res = mysql_query($sql) or die( "$sql<br/>" . mysql_error() );
        $num = mysql_num_rows($res);
        $row = mysql_fetch_assoc($res);
        $ipa = $row["ip_address"];
        $whn = $row["when_voted"];
        echo "<br/>";
        echo number_format($num);
        echo " VOTES FOR ";
        echo $color;
        if ($num)
        {
            echo " MOST RECENTLY ";
            echo $whn;
            echo " FROM IP ";
            echo $ipa;
            echo PHP_EOL;
        }
    }
    echo "<br/>" . PHP_EOL;
}


// CREATE THE FORM TO RECEIVE THE VOTES
echo '<form method="post">';
echo "VOTE FOR YOUR FAVORITE COLOR" . PHP_EOL;
foreach ($colors as $color)
{
    echo "<br/>";
    echo '<input type="checkbox" name="color_selections[';
    echo "$color";
    echo ']" />';
    echo $color;
    echo PHP_EOL;
}
echo '<br/><input type="submit" value="VOTE NOW" />' . PHP_EOL;
echo '</form>';

Open in new window

0
 

Author Closing Comment

by:jvsmooth
ID: 35021523
brilliant thank you so much
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 35021601
Glad to help.  Thanks for the points! ~Ray
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

OverviewThis article demonstrates a simple search form using AJAX. The purpose of the article is to demonstrate how to use the same code to render a page and javascript (JQuery) and AJAX to make subsequent calls to refine the results. The princip…
This article describes how to create custom column layout styles for Bootstrap. The article uses 5 columns to illustrate the concept, but the principle can be extended to any number of columns.
In this tutorial viewers will learn how to style a corner ribbon overlay for an image using CSS Create a new class by typing ".Ribbon":  Define the class' "display:" as "inline-block": Define its "position:" as "relative": Define its "overflow:" as …
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now