Créer une API de sondage en php et mysql

Tout d'abord, il faut créer une base de données sur votre serveur ou hébergement. Notez bien le nom de la base, le nom d'utilisateur et le mot de passe.

Dans phpMyAdmin, il faut ensuite créer la structure de la base avec le script :

CREATE TABLE `sondage` (
  `id` int(3) NOT NULL auto_increment,
  `reponse` varchar(200) default NULL,
  PRIMARY KEY  (`id`)
);

Création du fichier de connexion à la base de données en php :

<?php

// CONNEXION A LA BASE
$hostname_conn_vote = "localhost";
$database_conn_vote = "le-nom-de-votre-base";
$username_conn_vote = "nom-utilisateur";
$password_conn_vote = "mot-de-passe";

// GESTION DES ERREURS DE CONNEXION
$connexion_vote = mysql_connect($hostname_connexion_vote, $username_connexion_vote, $password_connexion_vote) or die('Erreur de connexion &agrave; le base de donn&eacute;s: '.mysql_error());
mysql_select_db($database_connexion_vote, $connexion_vote) or die('Erreur de connexion &agrave; le base de donn&eacute;s: '.mysql_error());

?>

Page de sondage

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<?php require_once('connexions/connexion_vote.php'); ?>
<?php
header("Content-Type: text/html;charset=UTF-8");

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO sondage (id, reponse) VALUES (%s, %s)",
                       GetSQLValueString($_POST['id'], "int"),
                       GetSQLValueString($_POST['Sondage'], "text"));

  mysql_select_db($database_connexion_vote, $connexion_vote);
  $Result1 = mysql_query($insertSQL, $connexion_vote) or die(mysql_error());

  $insertGoTo = "resultats.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}

$colname_rs_vote = "-1";
if (isset($_GET['recordID'])) {
  $colname_rs_vote = $_GET['recordID'];
}
mysql_select_db($database_connexion_vote, $connexion_vote);
$query_rs_vote = sprintf("SELECT * FROM sondage WHERE id = %s", GetSQLValueString($colname_rs_vote, "int"));
$rs_vote = mysql_query($query_rs_vote, $connexion_vote) or die(mysql_error());
$row_rs_vote = mysql_fetch_assoc($rs_vote);
$totalRows_rs_vote = mysql_num_rows($rs_vote);
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Sondage</title>
<link href="/style.css" rel="stylesheet" type="text/css" />
</head>

<body>


<fieldset>

    <legend>Est-ce que ce tutoriel est utile ?</legend>
    
    <form action="<?php echo $editFormAction; ?>" id="form1" name="form1" method="POST"  enctype="multipart/form-data" accept-charset="UTF-8">
    
    <table>
        <tr>
            <td>
                <input type="radio" name="Sondage" value="utile" id="Sondage_0" class="css-radio" />
                <label for="nuisiblerestaurationclassique_0" class="css-label">Utile</label>
            </td>
        </tr>
        <tr>
            <td>
                <input type="radio" name="Sondage" value="inutile" id="Sondage_1" class="css-radio" />
                <label for="nuisiblerestaurationclassique_1" class="css-label">Inutile</label>
            </td>
        </tr>
        <tr>
            <td>
                <input type="radio" name="Sondage" value="pas encore testé" id="Sondage_2" class="css-radio" />
                <label for="nuisiblerestaurationclassique_2" class="css-label">Pas encore testé</label>
            </td>
        </tr>
        <tr>
            <td>
                <input type="submit" name="submit" id="submit" value="Vote" />
            </td>
        </tr>
    </table>

    <input type="submit" name="submit" id="submit" value="Vote" />
    
    <input type="hidden" name="id" value="form1" />
    
    <input type="hidden" name="MM_insert" value="form1" />
</form>

</fieldset>

</body>
</html>


<?php
mysql_free_result($rs_vote);
?>

Page de résultats

<?php require_once('connexions/connexion_vote.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_connexion_vote, $connexion_vote);
$query_rs_vote = "SELECT * FROM sondage";
$rs_vote = mysql_query($query_rs_vote, $connexion_vote) or die(mysql_error());
$row_rs_vote = mysql_fetch_assoc($rs_vote);
$totalRows_rs_vote = mysql_num_rows($rs_vote);

$resultreponse1 = mysql_query("SELECT * FROM sondage WHERE reponse='utile'");
$num_rowsreponse1 = mysql_num_rows($resultreponse1);

$resultreponse2 = mysql_query("SELECT * FROM sondage WHERE reponse='inutile'");
$num_rowsreponse2 = mysql_num_rows($resultreponse2);

$resultreponse3 = mysql_query("SELECT * FROM sondage WHERE reponse='pas encore testé'");
$num_rowsreponse3 = mysql_num_rows($resultreponse3);

$percentreponse1 = ($num_rowsreponse1 / $totalRows_rs_vote)*100;
$percentreponse2 = ($num_rowsreponse2 / $totalRows_rs_vote)*100;
$percentreponse3 = ($num_rowsreponse3 / $totalRows_rs_vote)*100;

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Results</title>
    <link href="/style.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <fieldset>
    
        <legend>Results</legend>
        
        <ul>
            <li>
                <span class="total-votes"><?php echo $num_rowsreponse1 ?></span> Utile
                <br />
                <div class="results-bar" style="width: <?php echo round($percentreponse1,2); ?>%;">
                     <?php echo round($percentreponse1,2); ?>%
                </div>
            </li>
            
            <li>
                <span class="total-votes"><?php echo $num_rowsreponse2 ?></span> Inutile
                <div class="results-bar" style="width: <?php echo round($percentreponse2,2); ?>%;">
                     <?php echo round($percentreponse2,2); ?>%
                </div>
            </li>
        
            <li>
                <span class="total-votes"><?php echo $num_rowsreponse3 ?></span> Pas encore test&eacute;
                <div class="results-bar" style="width: <?php echo round($percentreponse3,2); ?>%;">
                     <?php echo round($percentreponse3,2); ?>%
                </div>
            </li>
        </ul>
    
        <h6>Total votes: <?php echo $totalRows_rs_vote ?></h6>
        
        <a href="/sondage.php">Retour au sondage</a>
    
    </fieldset>
    
</body>
</html>


<?php
mysql_free_result($rs_vote);
?>

Un peu de CSS pour fignoler l'affichage :

* {
    margin: 0;
    padding: 0;
}

body {
    font-size: 100%;
    font-family: 'helevtica neue', helvetica, arial, sans-serif;
    background: url('images/sondage.jpg') no-repeat center fixed;
    background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

h6 {
    font-size: 1.4em;
    margin-bottom: 15px;
}

a { color: white; }

label, li {
    display: block;
    padding: 5px 5px 5px 9px;
    font-size: 14px;
    color: #000;
}

fieldset {
    background: #FFF;
    background-color: rgba(255,255,255,0.9);
    margin: 115px auto 0;
    width: 500px;
    padding: 20px;
    display: block;
    border: 0;
    color: #000;
    -moz-box-shadow: 2px 2px 5px 0px #656565;
    -webkit-box-shadow: 2px 2px 5px 0px #656565;
    -o-box-shadow: 2px 2px 5px 0px #656565;
    box-shadow: 2px 2px 5px 0px #656565;
    filter:progid:DXImageTransform.Microsoft.Shadow(color=#656565, Direction=134, Strength=5);
}
legend {
    background: #000;
    background-color: rgba(0,0,0,1);
    padding: 6px 10px;
    border: 0;
    font-size: 21px;
    color: #fff;
}

input[type=radio].css-radio {
    position:absolute; z-index:-1000; left:-1000px; overflow: hidden; clip: rect(0 0 0 0); height:1px; width:1px; margin:-1px; padding:0; border:0;
}
input[type=radio].css-radio + label.css-label {
    padding-left:19px;
    height:14px;
    display:inline-block;
    line-height:14px;
    background-repeat:no-repeat;
    background-position: 0 0;
    font-size:14px;
    vertical-align:middle;
    cursor:pointer;
}
input[type=radio].css-radio:checked + label.css-label {
    background-position: 0 -14px;
}
label.css-label {
    background-image:url(images/css-radio.png);
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    margin-right: 20px;
}
    
ul { list-style: none; margin-bottom: 15px;}

.results-bar {
    padding: 10px;
    color: white;
    background: url(images/result-bar-bg.png) left center;
    white-space: nowrap;
}

span.total-votes {
    font-size: 2.6em;
}

Un peu de CSS pour fignoler l'affichage :

BLOG COMMENTS POWERED BY DISQUS