Jump to content
СофтФорум - всё о компьютерах и не только

Викторина


Recommended Posts

Помогите собрать html викторину вот такого вида.

Как это будет выглядеть? Надо будет делать несколько страниц? (по числу вопросов...)

Можно набросать небольшой конспектик? :rolleyes:

Link to comment
Share on other sites

Почему "html викторину" - тебе не нужно ответов в БД хранить?

У меня есть скрипт для вопросов, можно легко переделать чтоб работал не для одного (активного) вопроса а для всех из БД подрядь...

Пиши мне в ICQ

Link to comment
Share on other sites

Вот мой скрипт для анкет, к сожелению режим 'викторина' все еще не удалось доработать. В общем не сложно, если ктото хочеть дорабативать, я не знаю когда успею, в общем в окончательной версии будеть не только режим викторина, но и разние типи вопросов (с одним или с больше чем одним правильним ответом), но не знаю когда успею сделать. Сделаю - опобликую

А пока:

class.poll.php

<?phpclass Poll {public $question;public $id;public $answers = array();public $voted = false;public $votes = array();public function __construct($id, $data = false){	$this->id = $id > 0 ? $id : 0;	if ( $this->id && is_object( $data ) == false )	{		$sql = 'SELECT * FROM itl_polls WHERE id = '.intval( $id );		$data = DB::Instance()->query_first( $sql );	}	if ( is_object( $data ) )	{		$this->question = $data->question;		$this->answers = $this->_loadAnswers();		$this->votes = $this->_loadVotes();		$this->voted = $this->_checkVote();				} else {		$this->id = 0;	}}private function _loadAnswers(){	$sql = 'SELECT * FROM itl_answers WHERE poll_id='.$this->id;	$res = DB::Instance()->query( $sql );	$count = DB::Instance()->num_rows($res);	$answers = array();	for ($i = 0; $i < $count; $i++ )	{		$row = DB::Instance()->get_row($res);		$answers[ $row->id ] = $row->answer;	}	return $answers;}private function _loadVotes(){	$sql = 'SELECT answer_id, count(*) as count FROM itl_votes WHERE poll_id = '.$this->id.' GROUP BY answer_id';	$res = DB::Instance()->query( $sql );	$count = DB::Instance()->num_rows($res);	$votes = array();	for ($i = 0; $i < $count; $i++ )	{		$row = DB::Instance()->get_row($res);		$votes[ $row->answer_id ] = $row->count;	}	return $votes;}private function _checkVote(){	// check if user have voted for this poll	// 1st: check via cookie	if (is_array($_COOKIE['polls']) == false ) 	{		$_COOKIE['polls'] = array($_COOKIE['polls']);	}	if ( in_array( $this->id, $_COOKIE['polls'] ) )	{		$this->voted = true;		return true;	}	// 2nd: check via member_id		if ( isset($_SESSION['user']) ) 	{		$id = $_SESSION['user']->getUserID();		$sql = 'SELECT * FROM itl_votes WHERE answer_id IN ('.implode( ',', array_keys( $this->answers ) ).')';		$res = DB::Instance()->query( $sql );		if (DB::Instance()->num_rows($res) > 0)		{			$this->voted = true;			return true;		}	}	return false;}public function Vote($answer_id, $member_id, $ip){	if ( $this->voted ) 	{		return false;	}	if ( in_array($answer_id, array_keys($this->answers) ) == false )	{		return false;	}	$date = date("Y-m-d");	$sql = 'INSERT INTO itl_votes (answer_id, user_id, ip, date, poll_id) VALUES';	$sql .= sprintf( ' (%d, %d, "%s", "%s", %d) ', $answer_id, $member_id, $ip, $date, $this->id );	$res = DB::Instance()->query( $sql );	setcookie("polls[]", $this->id, time() + (60*60*24*365) );	$this->voted = true;	return true;}public function Update($data){	// TODO: Transaction	$DB = DB::Instance();	if ($this->id)	{		$sql = sprintf('UPDATE itl_polls SET question = "%s" WHERE id = %d', $DB->escape_string( $data['question'] ), $this->id );		$res = $DB->query( $sql );		// asnwers to remove		$deletedAnswers = array_diff( array_keys($this->answers), array_keys($data['answers'])  );		$sql = 'DELETE FROM itl_answers WHERE id IN ('.implode(',', $deletedAnswers).')';		$result = $DB->query( $sql );		foreach ( $data['answers'] as $id => $answer )		{			if ($id > 0)			{				$sql = sprintf('UPDATE itl_answers SET answer = "%s" WHERE id = %d', $DB->escape_string( $answer ), intval( $id ) );			} else {				$sql = sprintf('INSERT INTO itl_answers(poll_id, answer) VALUES(%d, "%s")', intval($this->id), $DB->escape_string( $answer ) );			}			$result = $DB->query( $sql );		}		return true;	}	$sql = sprintf('INSERT INTO itl_polls(question) VALUES ("%s")', $DB->escape_string( $data['question'] ) );	$result = $DB->query( $sql );	$id = $DB->insert_id();	foreach ( $data['answers'] as $a_id => $answer )	{		$sql = sprintf('INSERT INTO itl_answers(poll_id, answer) VALUES(%d, "%s")', $id, $DB->escape_string($answer) );		$result = $DB->query( $sql );	}	return true;}public function Delete(){	// TODO: Transaction	$sql = 'DELETE FROM itl_votes WHERE answer_id IN ('.implode( ',', array_keys( $this->answers ) ).')';	$result = DB::Instance()->query( $sql );	$sql = 'DELETE FROM itl_answers WHERE poll_id = '.$this->id;	$result = DB::Instance()->query( $sql );	$sql = 'DELETE FROM itl_polls WHERE id = ' . $this->id;	$result = DB::Instance()->query( $sql );	return true;}static public function GetPolls(){	$sql = 'SELECT * FROM itl_polls';	$res = DB::Instance()->query( $sql );	$count = DB::Instance()->num_rows($res);	$polls = array();	for ($i = 0; $i < $count; $i++)	{		$row = DB::Instance()->get_row($res);		$polls[] = new Poll($row->id, $row);	}	return $polls;}static public function GetCurrentPoll(){	$sql = 'SELECT * FROM itl_polls ORDER BY id DESC LIMIT 1';	$res = DB::Instance()->query( $sql );	$row = DB::Instance()->get_row($res);	$poll = new Poll($row->id, $row);	return $poll;}}?>

polls.php

<?if ( !defined("IN_ITL") ){header("Location: http://it-light.net");exit;}require_once( dirname(__FILE__).'/poll/class.poll.php' );class PollManager{protected $act;protected $html;protected $title;protected function ViewPolls(){	$admin = isset($_SESSION['user']) && $_SESSION['user']->isModerator();	$this->title = 'Àíêåòè';	$polls = Poll::GetPolls();	foreach ($polls as $poll)	{		$this->html .= '<a href="/index.php?category=polls&act=view&poll_id='.$poll->id.'">'.$poll->question.'</a>';		if ( $admin )		{			$this->html .= ' (<a href="/index.php?category=polls&act=edit&poll_id='.$poll->id.'">Ðåäàêòèðàé</a>)';		}		$this->html .= '<br />';	}	if ($admin)	{		$this->html .= '<a href="/index.php?category=polls&act=edit&poll_id=0">Äîáàâè</a>';	}}protected function View($id){	$poll = new Poll( $id );	$this->html .= '<b>'.$poll->question."</b><br>";	$this->html .= '<table border="0" cellpadding="0" cellspacing="0">';	$total = array_sum($poll->votes);	foreach ( $poll->answers as $id => $answer )	{		$count = isset($poll->votes[ $id ]) ? $poll->votes[ $id ] : 0;		$perc = ($total > 0 ) ? floor ( ( $count / $total ) * 100 ) : 0;		$this->html .= '<tr><td>'.$answer.'</td></tr>';		$this->html .= '<tr><td><img src="/bar.gif" width="'.($perc+1).'" height="10"> '.$count.'</td></tr>';	}	$this->html .= '<tr><td>Îáùî ãëàñóâàëè: '.$total.'</td></tr>';	$this->html .= '</table>';}protected function ViewCurrent(){	$poll = Poll::GetCurrentPoll();	if ($poll->voted)	{		return $this->View($poll->id);	}	if ( isset($_SESSION['post']['answer_id']) )	{		$member_id = (isset($_SESSION['user'])) ? $_SESSION['user']->getUserID() : 0;		$poll->Vote($_SESSION['post']['answer_id'], $member_id, $_SERVER['REMOTE_ADDR']);		return $this->View($poll->id);	}	$this->html .= '<form action=/dispatcher.php method=post>';	$this->html .= '<b>'.$poll->question."</b><br>";	foreach ($poll->answers as $id => $value )	{		$this->html .= '<input type=radio name=answer_id value='.$id.'>'.$value.'<br>';	}	$this->html .= '<div align=center><input type=submit value="Ãëàñóâàé"></div>';	$this->html .= '</form>';}protected function Edit($id){	$admin = isset($_SESSION['user']) && $_SESSION['user']->isModerator();	if ($admin == false)	{		return;	}	$poll = new Poll( $id );	if ( isset( $_SESSION['post']['question'] ) )	{		if ( $poll->Update( $_SESSION['post'] ) )		{			unset($_SESSION['post']);			return $this->ViewPolls();			}		// TODO: Some error handling		unset($_SESSION['post']);		return $this->ViewPolls();		}	$this->html .= '<form action=dispatcher.php method=post>';	$this->html .= '<input type=hidden name=forwardTo value="/index.php?category=polls&act=edit&poll_id='.$poll->id.'">';	$this->html .= '<table border="0" cellpadding="0" cellspacing="0">';	$this->html .= '<tr><td>Âúïðîñ:</td><td><input type=text name=question value="'.htmlspecialchars( $poll->question ).'">';	$this->html .= '<tr><td>Îòãîâîðè:</td><td>';	$this->html .= '<div id="answer-container">';	// TODO: Check max id	foreach ( $poll->answers as $id => $answer )	{		$this->html .= '<div id="answer-'.$id.'"><input type=text name=answers['.$id.'] value="'.htmlspecialchars( $answer ).'"> (<a href="java script:removeAnswer('.$id.')">Èçòðèé</a>) </div>';	}	$this->html .= '</div>';	$this->html .= '<div><a href="java script:addAnswer()">Äîáàâè</a></div>';	$this->html .= '</tr>';	$this->html .= '<tr><td colspan=2 align=right><input type=submit value="Ðåäàêòèðàé">';	$this->html .= '</table>';}public function process($act = ''){	switch ( $act )	{		case 'list':			$this->ViewPolls();			break;		case 'view':			$this->View($_GET['poll_id']);			break;		case 'edit':			$this->Edit($_GET['poll_id']);			break;		default :			$this->ViewCurrent();			break;	}}public function render(){	return $this->html;}public function getTitle(){	return $this->title;}}?>

Если ктото можеть дописивать, пишите и публикуйте новие изходники :cool:

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...