How to restrinc user votes - php

I implemented a vote system for my users on a forumbundle. It works fine but I would like to restrinct and just let vote 1 time for user. So I create a Boolean voted on my bdd.
But I don't know how should I can avoid that user's can vote again but at the same time I'd like to let them undo the vote.
So I made this function :
public function ScoreAction(Request $request){
$em = $this->getDoctrine()->getManager();
$idTopic = $request->request->get('id_topic');
$idPoster = $request->request->get('id_poster');
$positive= $request->request->get('positive');
$negative= $request->request->get('negatiu');
$user= $em->getRepository(User::class)->findOneById($idPoster);
$topic = $em->getRepository(Topic::class)->findOneById($idTopic);
$score= $user->getReputation();
$voted = $user->getVoted();
if ($positive!= null) {
$score= $score+ 1;
$voted = 1;
}
if($negative!= null){
$score= $score- 1;
$voted = 1;
}
$user->setReputation($score);
$user->setVoted($voted);
$em->persist($user);
$em->flush();
$redirect = $this->generateUrl('discutea_forum_post', array('slug' => $topic->getSlug()));
return $this->redirect($redirect);
}
Update with change boolean for int nullable on my Database and made this code:
$score = $user->getReputation();
$voted = $user->getVoted();
if ($voted == null) {
if ($positive != null) {
$score = $score + 1;
$voted = 1;
}
if($negative != null){
$score = $score - 1;
$voted = 0;
}
}else if($voted == 1){
if ($negative != null) {
$score = $score - 1;
$voted = 0;
}
}else if($voted == 0){
if ($positive != null) {
$score = $score + 1;
$voted = 1;
}
}
$user->setReputation($score);
$em->persist($user);
$em->flush();

$voted = $user->getVoted();
if ($voted) {
//just redirect somewhere else, without making an actual vote
} else {
//do your vote stuff
//persist and flush etc
//redirect somewhere else
}
something along those lines ?
are you trying to achieve the following ?:
$voted = $user->getVoted();
if ($voted) {
if ($positive!= null) {
$user->setReputation($user->setReputation()+2);
}
if ($negative!= null){
$user->setReputation($user->setReputation()-2);
}
} else {
if ($positive!= null) {
$user->setReputation($user->setReputation()+1);
}
if ($negative!= null){
$user->setReputation($user->setReputation()-1);
}
}
EDIT:
try this
if ($voted === null) {
if ($positive != null) {
$score = $score + 1;
}
if($negative != null){
$score = $score - 1;
}
}else if($voted === 1){
if ($negative != null) {
$score = $score - 1;
}
}else if($voted === 0){
if ($positive != null) {
$score = $score + 1;
}
}

Related

Auto Description From Tags

I'm trying to generate auto description from tags.
The code was working but after updating my site to Laravel 6 in stop working. I need to get it back working.
if( !empty( $request->description ) )
{
$description = Helper::checkTextDb($request->description);
}
else
{
$a_key = explode(",", strtolower($request->tags));
if(count($a_key) == 0)
$description = 'This is a great thing';
else
{
$description_get_keys = '';
foreach ($a_key as &$value)
{
if($value == end($a_key) && count($a_key) != 1)
$description_get_keys = $description_get_keys.' and '.$value.'.';
else if(count($a_key) == 1)
$description_get_keys = $value.'.';
else if (count($a_key) > 1 && $a_key[0] == $value)
$description_get_keys = $value;
else
$description_get_keys = $description_get_keys.', '.$value;
}
$description = 'This is a great thing about '.$description_get_keys;
}
}
I see a couple things that could possibly be an issue, not knowing what came before this code.
I will assume that the $request variable is an instance of Illuminate\Http\Request and that it is available in the function, right?
Try this updated code:
if($request->has('description'))
{
$description = Helper::checkTextDb($request->description);
}
else if ($request->has('tags'))
{
if (strpos($request->tags, ',') === false)
{
$description = 'This is a great thing';
}
else {
$a_key = explode(",", strtolower($request->tags));
$a_count = count($a_key);
$description_get_keys = '';
for ($i = 0; $i < $a_count; $i++)
{
if ($a_count == 1) {
$description_get_keys = "{$a_key[$i]}.";
}
else {
// first
if ($i === 0) {
$description_get_keys = $a_key[0];
}
// last
else if ($i === $a_count - 1) {
$description_get_keys .= " and {$a_key[$i]}.";
}
// middle
else {
$description_get_keys .= ", {$a_key[$i]}";
}
}
}
$description = "This is a great thing about {$description_get_keys}";
}
}
I wrote that quick so hopefully there are no errors.

Pass ID in URL PHP

Here's where I'm trying to get the ID
function addCliente($tipo_pessoa, $popup=null, $dados = null) {
$tipo_login = $this->session->userdata('tipo_login');
if ($this->session->userdata('logado') == true && $tipo_login == '1') {
$this->load->library('form_validation');
if ($tipo_pessoa == 1) {
$this->form_validation->set_rules('cpf', 'CPF', 'required|callback_verifica_cpf');
} else if ($tipo_pessoa == 2) {
$this->form_validation->set_rules('cnpj', 'CNPJ', 'required|callback_verifica_cnpj');
}
if ($this->form_validation->run() == FALSE) {
$this->returnCadCliente($tipo_pessoa);
} else {
$id_endereco = $this->cadEndereco($tipo_pessoa);
if ($tipo_pessoa == '1') {
$id_pessoa = $this->cadPessoaFisica();
$id_banco = $this->cadastroDadosBancarios();
$id_contato = $this->cadastroContato();
$id_cadastroAnexo = $this->cadastroAnexo();
$id_cadastroAtendimento = $this->cadastroAtendimento();
} else if ($tipo_pessoa == '2') {
$id_pessoa = $this->cadPessoaJuridica();
$id_banco = $this->cadastroDadosBancarios();
$id_contato = $this->cadastroContato();
$id_cadastroAnexo = $this->cadastroAnexo();
$id_cadastroAtendimento = $this->cadastroAtendimento();
}
$limite_credito = null;
if ($this->input->post('limite_credito')) {
$limite_credito = $this->input->post('limite_credito');
}
$id_cliente = $this->cadCliente($tipo_pessoa);
$data_cad = date("d/m/Y");
$hora_cad = date("H:i:s");
if ($id_cadastro = $this->cadastroComum($limite_credito, (int) $tipo_pessoa, $id_pessoa, 1, $id_cliente, $id_endereco, $data_cad, $hora_cad)) {
$this->cadastroHistorico('Cliente cadastrado', $id_cadastro, $data_cad, $hora_cad);
if ($popup == '1') {
$this->mensagemAlerta("Cliente cadastrado com sucesso!", 1, "home/cadastroOrcamentoVenda/" . $this->input->post('matricula'), (int) $tipo_pessoa);
} else {
//$this->mensagemAlerta("Cliente cadastrado com sucesso!", 1, "home/cadastroCliente/", (int) $tipo_pessoa);
I call alteraçãoClientePf here
$this->mensagemAlerta("Cliente cadastrado com sucesso!", 1, "home/alteracaoClientePf/" . $this->input->post('id_cadastro'), (int) $tipo_pessoa);
}
} else {
$this->mensagemAlerta("Erro ao cadastrar cliente, tente novamente!", 0, "cadastro/returnCadCliente/", (int) $tipo_pessoa);
}
}
} else {
$dados['mensagem'] = null;
$this->load->view('login/head');
$this->load->view('login/formLogin', $dados);
$this->load->view('login/footer');
}
}
This is the function I call when requesting the ID
function alteracaoClientePf($id_cadastro, $dados = null) {
$tipo_login = $this->session->userdata('tipo_login');
if ($this->session->userdata('logado') == true && $tipo_login == '1') {
$dadosCliente['dados'] = $this->lista->retornaDadosClientePf($id_cadastro);
$dadosCliente['banco'] = $this->adm->returnBancos();
$dadosCliente['contas_bancarias'] = $this->lista->retornaContas($id_cadastro);
$dadosCliente['contatos'] = $this->lista->retornaContatos($id_cadastro);
$dadosCliente['anexos'] = $this->lista->retornaAnexos($id_cadastro);
$dadosCliente['atendimentos'] = $this->lista->retornaAtendimentos($id_cadastro);
$dadosCliente['historico'] = $this->lista->retornaHistorico($id_cadastro);
$this->load->view('admin/head');
$dadosBarra['dadosB'] = $this->financeiro->listaContas();
$this->load->view('admin/barraSuperior', $dadosBarra);
$dadosLogo['logo'] = $this->adm->retornaLogo();
$this->load->view('admin/menu', $dadosLogo);
$this->load->view('admin/alteracoes/alterar_cliente_pf', $dadosCliente);
$this->load->view('admin/footer');
} else {
$dados['mensagem'] = null;
$this->paginas($dados);
}
}
That's the error I'm getting
Message: Too few arguments to function Home::alteracaoClientePf(), 0 passed in C:\xampp\htdocs\sistema_financas_old_atual\system\core\CodeIgniter.php on line 532 and at least 1 expected
Filename: C:\xampp\htdocs\sistema_financas_old_atual\application\controllers\Home.php
Line Number: 1184

how to write recursion using loops

I want to write recursive code using loops instead of recursion function. because recursion take too much time to execute and even fails.This is counting user in both side of binary tree using recursion.i want to achieve this task using loops. please help me to achieve this task.thanks in advance.I will very thank full to you.
function countActiveMembers($mid){
if ($mid == null) {
return 0;
}
$c = 0;
include("conn.php");
$query = $conn->prepare('SELECT leftm, rightm, package_choose FROM member WHERE user_id = ?');
$query->bind_param('s', $mid);
$query->execute();
$query->bind_result($leftm, $rightm, $package_choosen);
if ($query->fetch()) {
$query->close();
$conn->close();
if ($package_choosen == 1) {
$c = 0;
} else {
$c = 1;
}
if (isset($leftm) == false && isset($rightm) == false) {
return $c;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($leftm);
}
if (isset($rightm)) {
$c = $c + countActiveMembers($rightm);
}
} else {
$query->close();
$conn->close();
}
return $c;
}
function countLeftActive($mid){
if ($mid == null) {
return 0;
}
$c = 0;
include("conn.php");
$query = $conn->prepare('SELECT leftm, rightm, package_choose FROM member WHERE user_id = ?');
$query->bind_param('s', $mid);
$query->execute();
$query->bind_result($leftm, $rightm, $package_choosen);
if ($query->fetch()) {
$query->close();
$conn->close();
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($leftm);
}
} else {
$query->close();
$conn->close();
}
return $c;
}
function countRightActive($mid){
if ($mid == null) {
return 0;
}
$c = 0;
include("conn.php");
$query = $conn->prepare('SELECT leftm, rightm, package_choose FROM member WHERE user_id = ?');
$query->bind_param('s', $mid);
$query->execute();
$query->bind_result($leftm, $rightm, $package_choosen);
if ($query->fetch()) {
$query->close();
$conn->close();
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($rightm)) {
$c = $c + countActiveMembers($rightm);
}
} else {
$query->close();
$conn->close();
}
return $c;
}
I hope you can appreciate that this is difficult to test, so hopefully you can understand it enough to help.
One of the big performance issues in any system is file/database access and opening and closing connections etc. is always a slow process. This routine loads all the members in the start and passes the data around rather than continually using the database...
function countActiveMembers( $members, $mid){
if ($mid == null) {
return 0;
}
$c = 0;
// Fetch the data from the $members list, using $mid as the index
$leftm = $members[$mid]['leftm'];
$rightm = $members[$mid]['rightm'];
$package_choosen = $members[$mid]['package_choose'];
if ($package_choosen == 1) {
$c = 0;
} else {
$c = 1;
}
if (isset($leftm) == false && isset($rightm) == false) {
return $c;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($members, $leftm);
}
if (isset($rightm)) {
$c = $c + countActiveMembers($members, $rightm);
}
return $c;
}
function countLeftActive($members, $mid){
if ($mid == null) {
return 0;
}
$c = 0;
$leftm = $members[$mid]['leftm'];
$rightm = $members[$mid]['rightm'];
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($members, $leftm);
}
return $c;
}
function countRightActive($members, $mid){
if ($mid == null) {
return 0;
}
$c = 0;
$leftm = $members[$mid]['leftm'];
$rightm = $members[$mid]['rightm'];
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($rightm)) {
$c = $c + countActiveMembers($members, $rightm);
}
return $c;
}
// Use your own database credentials
$conn = mysqli_connect("172.17.0.3", "root","a177fgvTRw", "test" );
$result = $conn->query('SELECT user_id, leftm, rightm, package_choose
FROM member');
$members = [];
// Read all the members in and index them by the user_id
while ($row = $result->fetch_assoc()) {
$members[$row["user_id"]] = $row;
}
// Not entirely sure how you use it,but this shows passing the members into the start function
echo countActiveMembers($members, 1);

Check and modify Capitalized letters in string

I'm trying to figure out how to make this code work.
I input some text via variable into code:
$genome = "ss/ee/ff/Nn/oo";
$gepieces = explode("/", $genome);
$fenome = "ss/Ee/ff/nn/oo";
$fepieces = explode("/", $fenome);
You will see that for the Genome there is a Nn and for the Fenome there is a Ee
Upon this happening I need it to give a 50/50 chance for a compared result to be EITHER Ee OR Nn - The code I have right now can only check them individually (so sometimes I ger Ee AND Nn, other times I will get ee and nn) and I feel there could be a much easier method of achieving this than what I'm trying:
//Number of Cubs
$cubs = rand(1,4);
//GENDER
for ($x = 0; $x < $cubs; $x++) {
$gender = rand(1,2);
if ($gender == 1) {
$cubgender = "Male";
} elseif ($gender == 2) {
$cubgender = "Female";
}
//COAT COLOR
$genome = "ss/ee/ff/Nn/oo/Pa/Sr/So";
$gepieces = explode("/", $genome);
$fenome = "ss/Ee/ff/nn/oo/Pa";
$fepieces = explode("/", $fenome);
if ($gepieces[0] === $fepieces[0]) {
$ss = $gepieces[0];
} else {
$ss = rand(1,2);
if ($ss == 1) {
$ss = $gepieces[0];
} else {
$ss = $fepieces[0];
}
}
if ($gepieces[1] === $fepieces[1]) {
$ee = $gepieces[1];
} else {
$ee = rand(1,2);
if ($ee == 1) {
$ee = $gepieces[1];
} else {
$ee = $fepieces[1];
}
}
if ($gepieces[2] === $fepieces[2]) {
$ff = $gepieces[2];
} else {
$ff = rand(1,2);
if ($ff == 1) {
$ff = $gepieces[2];
} else {
$ff = $fepieces[2];
}
}
if ($gepieces[3] === $fepieces[3]) {
$nn = $gepieces[3];
} else {
$nn = rand(1,2);
if ($nn == 1) {
$nn = $gepieces[3];
} else {
$nn = $fepieces[3];
}
}
if ($gepieces[4] === $fepieces[4]) {
$oo = $gepieces[4];
} else {
$oo = rand(1,2);
if ($oo == 1) {
$oo = $gepieces[4];
} else {
$oo = $fepieces[4];
}
}
echo $cubgender." - ".$ss."/".$ee."/".$ff."/".$nn."/".$oo."<br/>";
}
I'm a colossal idiot!
Figured out my own issue
//Number of Cubs
$cubs = rand(1,4);
//GENDER
for ($x = 0; $x < $cubs; $x++) {
$gender = rand(1,2);
if ($gender == 1) {
$cubgender = "Male";
} elseif ($gender == 2) {
$cubgender = "Female";
}
//COAT COLOR
$genome = "ss/ee/ff/Nn/oo";
$gepieces = explode("/", $genome);
$fenome = "ss/Ee/ff/nn/oo";
$fepieces = explode("/", $fenome);
if ($genome === $fenome) {
$cubgeno = $genome;
} else {
$cubgeno = rand(1,2);
if ($cubgeno == 1) {
$cubgeno = $genome;
} else {
$cubgeno = $fenome;
}
}
echo $cubgender." - ".$cubgeno."<br/>";
$genome = "ss/ee/ff/Nn/oo/Pa/Sr/So";
$gepieces = explode("/", $genome);
$fenome = "ss/Ee/ff/nn/oo/Pa";
$fepieces = explode("/", $fenome);
$sequence = "";
for ($i = 0;$i < count($fepieces); $i++) {
rand(1,2) == 1 ? $sequence .= $gepieces[$i] : $sequence .= $fepieces[$i];
}
echo $sequence;

Ajax response not displaying anything in view file (Yii)

I have a file ( _gen.php) that is in my view that sends selected data to the controller file for verification:
$('#validate').on('click',function(){
var data = []; // data container
// collect all the checked checkboxes and their associated attributes
$("table#subsection_table input[type='checkbox']:checked").each(function(){
data.push({
section : $(this).data('sectionid'),
subsection : $(this).val(),
year : $(this).data('year')
})
});
// JSON it so that it can be passed via Ajax call to a php page
var data = JSON.stringify(data);
$.ajax({
url : "<?php echo Yii::app()->createAbsoluteUrl("scheduler/ScheduleValidation"); ?>",
type: "POST",
data : "myData=" + data,
success : function(data)
{
$("#ajax-results").html(data);
$("#ajax-results").dialog({ width: 500, height: 500})
},
error: function()
{
alert("there was an error")
}
})
console.log(JSON.stringify(data));
$('#dialog').html(data).dialog({ width: 500, heigh: 500});
});
Now #ajax-result is the id of one of my div tag after my button ( last thing displayed on the page).
As for the controller function, I do know it handles the data fine and the sql call correctly ( I made sure of it). However when I call renderPartial it will call my _ajax.php file correctly but it will only displayed it in an alert box, not to the #ajax-result tag. The controller function:
public function actionScheduleValidation()
{
print_r("in ajax");
$post_data = $_POST['myData'];
$decodedData = json_decode($post_data, true);
//$course = [[[]]];
$course=[];
$counter = 0;
//Save the years associated to sections chosen
foreach ($decodedData as $key) {
$tutOrLab = null;
$lec = null;
$currentYear = null;
foreach ($key as $id => $number) {
if ($id == 'year') {
$currentYear = $number;
} elseif ($id == 'subsection') {
$tutOrLab = Yii::app()->db->createCommand()
->select('courseID,kind,days,start_time,end_time,semester')
->from($id)
->where('id=' . $number)
->queryRow();
} else
$lec = Yii::app()->db->createCommand()
->select('courseID,kind,days,start_time,end_time,semester')
->from($id)
->where('id=' . $number)
->queryRow();
}
print_r(gettype($lec['start_time']));
$lecture = new Lecture($lec['courseID'],$lec['kind'],$lec['days'],$lec['start_time'],$lec['end_time'],$lec['semester'],$currentYear);
print_r(gettype($lecture->getStartTime()));
// WILL ACTUALLY DISPLAY SOMETHING
$tutorial = new TutorialAndLab($tutOrLab['courseID'],$tutOrLab['kind'],$tutOrLab['days'],$tutOrLab['start_time'],$tutOrLab['end_time'],$tutOrLab['semester'],$currentYear);
$course[$counter] = new CourseObj($lecture,$tutorial);
$counter++;
}
$courseYear1Fall = [];
$courseYear1Winter = [];
$courseYear2Fall = [];
$courseYear2Winter = [];
$courseYear3Fall = [];
$courseYear3Winter = [];
$courseYear4Fall = [];
$courseYear4Winter = [];
if($course != null) {
for ($i = 0; $i < count($course); $i++) {
if ($course[$i]->getLecture()->getYear() == '1') {
if ($course[$i]->getLecture()->getSemester() == 'F') {
array_push($courseYear1Fall, $course[$i]);
} elseif ($course[$i]->getLecture()->getSemester() == 'W') {
array_push($courseYear1Winter, $course[$i]);
}
} elseif ($course[$i]->getLecture()->getYear() == '2') {
if ($course[$i]->getLecture()->getSemester() == 'F') {
array_push($courseYear2Fall, $course[$i]);
} elseif ($course[$i]->getLecture()->getSemester() == 'W')
array_push($courseYear2Winter, $course[$i]);
} elseif ($course[$i]->getLecture()->getYear() == '3') {
if ($course[$i]->getLecture()->getSemester() == 'F') {
array_push($courseYear3Fall, $course[$i]);
} elseif ($course[$i]->getLecture()->getSemester() == 'W') {
array_push($courseYear3Winter, $course[$i]);
}
} elseif ($course[$i]->getLecture()->getYear() == '4') {
if ($course[$i]->getLecture()->getSemester() == 'F') {
array_push($courseYear4Fall, $course[$i]);
} elseif ($course[$i]->getLecture()->getSemester() == 'W') {
array_push($courseYear4Winter, $course[$i]);
}
}
}
$counter2=0;
$errorArr = [];
if($courseYear1Fall != null){
$fallErr = verification($courseYear1Fall);
$errorArr[$counter2] = $fallErr;
$counter2++;
}
elseif($courseYear1Winter != null) {
$winterErr = verification($courseYear1Winter);
$errorArr[$counter2] = $winterErr;
$counter2++;
}
if($courseYear2Fall != null) {
$fallErr = verification($courseYear2Fall);
$errorArr[$counter2] = $fallErr;
$counter2++;
}
if($courseYear2Winter != null) {
$winterErr = verification($courseYear3Fall);
$errorArr[$counter2] = $winterErr;
$counter2++;
}
if($courseYear3Winter != null) {
$fallErr = verification($courseYear3Fall);
$errorArr[$counter2] = $fallErr;
$counter2++;
}
if($courseYear3Fall != null) {
$winterErr = verification($courseYear3Winter);
$errorArr[$counter2] = $winterErr;
$counter2++;
}
if($courseYear4Fall != null) {
$fallErr = verification($courseYear4Fall);
$errorArr[$counter2] = $fallErr;
$counter2++;
}
if($courseYear4Winter != null) {
$winterErr = verification($courseYear4Winter);
$errorArr[$counter2] = $winterErr;
}
$this->renderPartial('_ajax', array(
'data' => $errorArr,
)
);
}
Any idea on how to append it to my original (_gen.php) html code?
Your ajax call is missing semi-colon.
And probably as a good practise you should not be naming both request and response variable "data".

Categories