We value your privacy

We use cookies to enhance your browsing experience, serve personalized ads or content, and analyze our traffic. By clicking "Accept All", you consent to our use of cookies.

Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Skip to content

Mihai Baboi

Vorbim despre mașini, tehnologie și nu numai

Menu
  • Home
  • Despre mine
  • Despre blog
  • Contact
  • Privacy Policy
Menu

Intreaba-ma: Sistem de votare pentru o lista de obiecte

Posted on March 16, 2011

O sa vedem in acest articol un exemplu rapid pentru rezolvarea unei probleme cu care m-a abordat un cititor. Sa vedem despre ce este vorba.

Avem o lista de elemente, sa zicem melodii, ordonate dupa note. In dreptul fiecarei melodii utilizatorul are posibilitatea sa dea o nota pentru a o ridica in clasament. Dupa vot, trebuie sa fim redirectati inapoi la lista ordonata dupa noile note.

O sa rezolvam aceasta problema in cativa pasi simpli, pentru ca lucrurile sa fie cat mai clare. Pentru ca exemplul sa fie complet, eu am sa includ si fisierul care defineste baza de date cu care vom lucra.

Sa vedem, deci, cum arata structura bazei de date:

CREATE DATABASE music_test;

USE music_test;

CREATE TABLE song
(
	id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
	name VARCHAR(64) NOT NULL,
	rating INT NOT NULL
);

INSERT INTO song(name, rating) VALUES('Calexico - Pepita', 0);
INSERT INTO song(name, rating) VALUES('Clannad - I Will Find You', 0);
INSERT INTO song(name, rating) VALUES('Sven Van Hees - Flute Salad', 0);
INSERT INTO song(name, rating) VALUES('M.O.P. - Cold As Ice', 0);
INSERT INTO song(name, rating) VALUES('Gloria Gaynor - I Love You Baby', 0);
INSERT INTO song(name, rating) VALUES('Queen - Love of My Life', 0);
INSERT INTO song(name, rating) VALUES('Sally Oldfield - Mirror', 0);
INSERT INTO song(name, rating) VALUES('Linkin Park - Somewhere I Belong', 0);
INSERT INTO song(name, rating) VALUES('Holograf - Viata Are Gust', 0);
INSERT INTO song(name, rating) VALUES('Joey Diggs - Always Coca-Cola', 0);
INSERT INTO song(name, rating) VALUES('Mission Belle - Just What I Want', 0);
INSERT INTO song(name, rating) VALUES('Dj Bobo - Chihuahua', 0);

Dupa cum se vede, avem o tabela simpla in care tinem un id (pentru identificare unica), un nume si nota pe care a primit-o melodia. Observati ca toate melodiile pleaca de la nota zero.

Sa vedem acum fisierul index.php unde vom afisa melodiile si de unde utilizatorii vor putea vota

<!DOCTYPE html>
<html>

<head>
	<title>Lista melodii</title>
	<style type="text/css">
		body {
			font-family: sans-serif;
			font-size: 13px;
			color: #000;
		}

		table tr td {
			padding: 3px;
		}

		#wrapper {
			width: 304px;
			padding: 15px;
			border: 1px solid #CCC;
			margin: auto;
		}
	</style>
</head>

<body>
	<div id="wrapper">
		<form method="post" action="save.php">
			<?php include("table.php"); ?>
			<div style="text-align: right; margin: 0px; padding: 0px">
				<input type="submit" value="Voteaza" />
			</div>
		</form>
	</div>
</body>

</html>

Este o structura HMTL simpla, dar o scriem intr-un fisier cu extensia .php pentru a putea diviza putin codul. Astfel, observati ca includem la un moment dat fisierul table.php. Sa vedem cum arata el si ce face:

<?php

$con = mysql_connect("localhost", "root", "root");

if(!$con)
{
	die('Could not connect: ' . mysql_error());
}

mysql_select_db("music_test", $con);

$sql  = "SELECT ";
$sql .= "	s.* ";
$sql .= "FROM ";
$sql .= "	song s ";
$sql .= "ORDER BY ";
$sql .= "	rating DESC, ";
$sql .= "	id ASC ";

$result = mysql_query($sql);

$table  = sprintf("<table border=\"1\">");
$table .= sprintf("	<tr>");
$table .= sprintf("		<th>ID</th>");
$table .= sprintf("		<th>Nume</th>");
$table .= sprintf("		<th>Nota</th>");
$table .= sprintf("		<th>Vot</th>");
$table .= sprintf("	</tr>");

while($row = mysql_fetch_array($result))
{
	$table .= sprintf("<tr>");
	$table .= sprintf("	<td>%s</td>", $row["id"]);
	$table .= sprintf("	<td>%s</td>", $row["name"]);
	$table .= sprintf("	<td>%s</td>", $row["rating"]);
	$table .= sprintf("	<td><input type=\"radio\" name=\"rating\" value=\"%s\" /></td>", $row["id"]);
	$table .= sprintf("</tr>");
}

$table .= sprintf("</table>");

mysql_close($con);

echo $table;

?>

Codul acesta nu face altceva decat sa aduca din baza de date lista de melodii ordonata dupa note si sa genereze un tabel pe baza ei. In plus, adauga in dreptul fiecarei melodii un buton radio prin intermediul caruia se poate vota.

Butonul radio are valoarea egala cu id-ul melodiei dintr-un motiv simplu. Nu avem nevoie de o nota. Ea va fi intotdeauna nota actuala plus unu. Avem nevoie in schimb, de id pentru a sti ce inregistrare sa actualizam.

Sa vedem asadar cum arata fisierul catre care trimite formularul. Acesta se numeste save.php si face cateva lucruri:

<?php

$con = mysql_connect("localhost", "root", "root");

if (!$con)
{
	die('Could not connect: ' . mysql_error());
}

mysql_select_db("music_test", $con);

$id = $_POST["rating"];

$sql  = "SELECT ";
$sql .= "	s.* ";
$sql .= "FROM ";
$sql .= "	song s ";
$sql .= "WHERE ";
$sql .= "	id = $id ";

$result = mysql_query($sql);

$row = mysql_fetch_array($result);
$rating = $row["rating"] + 1;

$insert = "UPDATE song SET rating = $rating WHERE id = $id";

mysql_query($insert);

mysql_close($con);

header("Location: index.php");

?>

In primul rand fisierul aduce din baza de date inregistrarea asupra careia se face actualizarea. Dupa ce am identificat melodia, ii incrementam nota cu 1 si actualizam inregistrarea in baza de date. In final, trebuie sa trimitem utilizatorul inapoi la lista de melodii.

Rezultatul dupa cateva voturi acordate, va arata in felul urmator:

La final, va las cu o arhiva pe care o puteti descarca si incerca la voi pe calculator. In felul acesta puteti studia si rafina codul in functie de nevoile voastre.

Descarca Demo

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Related

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Analiză Tehnică
  • Auto
  • Comunicate
  • Concurs
  • Diverse
  • Evenimente
  • Foto
  • Hardware
  • Întreabă-mă
  • Lansări
  • Mașini
  • Noutăți auto
  • Opinie
  • Programare
  • Review
  • Scurte
  • Șed și Cuget
  • Zvonuri

allview Android aspect asus autonomie browser bune practici camera CodeIgniter Code Igniter Cold Fusion concurs css3 display div dual core Evolio evoMAG evoMAG.ro foto hardware HTC html html5 instalare lansare laptop Library libris.ro marketonline nokia performanta pret programare review samsung Samsung Galaxy S II smartphone specificatii standarde Symbian tableta teste upgrade user experience

©2025 Mihai Baboi | Design: Newspaperly WordPress Theme
Menu
  • Home
  • Despre mine
  • Despre blog
  • Contact
  • Privacy Policy