Menu
  • HOME
  • TAGS

How to add +1 value to php

Tag: php,html,ajax,database

So I am making a pie chart with only PHP and Ajax. But I can't see how I must code further to make it work (see the first picture). So when someone clicks on button A B C or D, it must be seen (without page loading) that you have voted for one of them and also be seen in the chart. Actually that is it! The second image shows my database.

enter image description here

Before I forget to tell I DO NOT have a picture in my database to change.

enter image description here

I hope some of you can help me with this. Some of my code:

<p><h1>Breng jou stem uit</h1></p><br />
<form action = "<?php
echo $_SERVER['PHP_SELF'];
?>" method = "GET"> 
<button type="button" name="a">Partij A</button><br />
<button type="button" name="b">Partij B</button><br />
<button type="button" name="c">Partij C</button><br />
<button type="button" name="d">Partij D</button>
 </form>
<?php

// Connects to your Database

include('../../../connection.php');

$sql = mysql_query("SELECT * FROM votes");

while ($row = mysql_fetch_array($sql)) {
echo $partijA = $row['partijA'];
$partijB = $row['partijB'];
$partijC = $row['partijC'];
$partijD = $row['partijD'];
if (isset($_GET['a'])) {
    echo $resultA = $partijA + 1;
} else {
    echo "1";
}

$resultB = $partijB + 1;
$resultC = $partijC + 1;
$resultD = $partijD + 1;
}

// Name of our cookie

$cookie = "Voted";

// A function to display our results - this refrences vote_pie.php which we     will also make

function pie()
{
    $data = mysql_query("SELECT * FROM votes") or die(mysql_error());
    $result = mysql_fetch_array($data);
    $total  = $result[partijA] + $result[partijB] + $result[partijC] +      $result[partijD];
    $one    = round(360 * $result[partijA] / $total);
    $two    = round(360 * $result[partijB] / $total);
    $per1   = round($result[partijA] / $total * 100);
    $per2   = round($result[partijB] / $total * 100);
    $per3   = round($result[partijC] / $total * 100);
    $per4   = round($result[partijD] / $total * 100);
    echo "<img src=vote_pie.php?one=" . $one . "&two=" . $two . "><br/>";
    Echo "<font color=000000>Partij A</font> = $result[partijA] votes = $per1 <br /> 
         <font color=000000>Partij B</font> = $result[partijB] votes = $per2 <br />
         <font color=000000>Partij C</font> = $result[partijC] votes =  $per3 <br /> 
         <font color=000000>Partij D</font> = $result[partijD] votes = $per4 <br />";
}

// displays the poll results

pie();
?>

Best How To :

There are a number of problems in your code, but the one that causes the actual problems you're having is the fact that your function pie does not increment the values you fetched from the DB, that's done outside of the function, but the incremented values aren't used there:

function pie()
{
    //this query was already performed, pass the result resource to this function, don't re-run the query
    $data = mysql_query("SELECT * FROM votes") or die(mysql_error()); //google or die must die
    $result = mysql_fetch_array($data);//mysql is deprecated
    //array keys need to be quoted
    $total  = $result[partijA] + $result[partijB] + $result[partijC] +      $result[partijD];
    $one    = round(360 * $result[partijA] / $total);
    $two    = round(360 * $result[partijB] / $total);
    $per1   = round($result[partijA] / $total * 100);
    $per2   = round($result[partijB] / $total * 100);
    $per3   = round($result[partijC] / $total * 100);
    $per4   = round($result[partijD] / $total * 100);
    //functions return, they don't echo
    echo "<img src=vote_pie.php?one=" . $one . "&two=" . $two . "><br/>";
    Echo "<font color=000000>Partij A</font> = $result[partijA] votes = $per1 <br /> 
         <font color=000000>Partij B</font> = $result[partijB] votes = $per2 <br />
         <font color=000000>Partij C</font> = $result[partijC] votes =  $per3 <br /> 
         <font color=000000>Partij D</font> = $result[partijD] votes = $per4 <br />";
}

I've taken the liberty of adding some comments to point out several issues with the code.

Just remove the code that queries and increments outside of the pie function, and have your function do all of the work. Pass it the values it needs (ie $_GET, and have it return the result, instead of echoing it).
I'd rewrite the function to take arguments like so (not going into not using mysql at this point):

function getPie(array $params, $connection)
{
    //added limit 1, seeing as you're only processing the first result
    $result = mysql_query($connection, 'SELECT * from votes LIMIT 1');
    $row = mysql_fetch_assoc($result);
    if (isset($params['a'])) {
        $row['partijA'] += 1;
    } else if (isset($params['b'])) {
        $row['partijB'] += 1;
    } //add more else's for all parties
    $percentages = [];//array
    foreach ($row as $key => $val) {
        $percentages[$key] = round(($val/$total) * 100);
    }
    $total = array_sum($row);//total of all votes
    $markup = '<img src=vote_pie.php?one=' .
      $percentages['partijA']*360 . '&two=' . $percentages['partijB']*360 . '><br>';
    foreach ($percentages as $k => $perc) {
        $markup .= '<font color=000000>Partij ' . str_replace('partij', $k) . '</font> = '.
            $row[$key] . ' votes = ' . $perc . '<br>';
    }
    return $markup;
}

Then call this function like so:

if ($_GET) {//if a get form was submitted
    echo getPie($_GET, $db);//where $db holds the mysql resource
}

That's just a quick-fix, though... there's still a long way to go...

What I changed:

A quick canter through the actual changes I've made:

  • Passing arguments to the function: the function now takes 2 arguments, an array (the $_GET values in this case), and the db connection to use.
  • Loops instead of repetition: instead of repeating round($resutl['key']/total*100), I've used a loop, so I only have to write this statement once, and have it applied to all values
  • use an array for the percentages: Instead of assigning the percentage for each party to a new variable, I've opted to use an array instead. This keeps data that belongs together, well... together
  • Loops to create markup: Though I find stringing together markup bad practice, I've noticed most of the HTML is actually identical, so instead of hard-coding everything, I simply iterate over either the $row or $percentages array (they both have the same keys), and fill in the specific values. This also means that I can safely add a party without having to change the code that creates markup

compare today's date with unix timestamp value in database

php,mysql

If I understand correctly you have a unix timestamp in a varchar field and you can't change this. If you compare the unix timestamp directly you will only get results that match the exact second of the timestamp. You can use FROM_UNIXTIME() to convert the timestamp in a date value...

Include both local and server at the same time

php

file_exists: http://php.net/manual/en/function.file-exists.php is_dir: http://php.net/manual/en/function.is-dir.php Best way to do that is use dirname(__FILE__) which gets the directory's full path of the current file in ether unix of windows format. Then we use realpath() which conveniently returns false if file does not exist. All you have to do is specify a relative...

CSS - Linear Gradient Background Color no-repeat is not working for if it has multiple tds

html,css,css3

table{border-collapse:collapse;width:100%} table tr td{padding:5px;border:1px solid #000; background:#FFF } table tr:hover td{padding:5px;border:1px solid #000; background:transparent } table{ background:...

Codeigniter PHP Mailer, Sender Info

php,email,codeigniter-2,phpmailer,contact-form

Don't do that. It's effectively forging the from address and will fail SPF checks. Instead, use your own address as the From address, and add the submitted address as a reply-to address. In PHPMailer: $mail->From = '[email protected]'; $mail->addReplyTo($POST['emailfrom']); ...

Php Mysql Query not working properly

php,mysql

No need to use union as it will give a lots of duplicate data What you want to achieve can be done with simple left join or inner join SELECT m.issue_name ,m.issue_type , m.priority ,m.status,m.description , m.start_date,m.end_date,m.duration, s.name as server_name,p.name as product_name from mod_networkstatus as m LEFT JOIN tblservers as...

Centering navbar pills vertically within the navbar using flexbox

html,css,twitter-bootstrap,flexbox

Set display: flex for the <ul class="nav">, not for items. Also use align-items: center for vertical aligment: .nav { height: 70px; display: flex; justify-content: center; align-items: center; } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> <div class="container"> <nav class="navbar navbar-default navbar-fixed-top"> <ul id="nav_pills" class="nav nav-pills" role="tablist"> <li role="presentation"> <a href="/">About</a> </li> <li...

Composer dump-autoload gives preg_match error

php,composer-php,autoload

autoload should be moved out of require-dev: { "require-dev":{ "phpunit/phpunit":"4.5.*" }, "autoload":{ "psr-0":{ "Yii\\":"yii-1.1.14.f0fee9/" } } } You can test your composer.json file using composer validate. Your original file returned: ./composer.json is invalid, the following errors/warnings were found: require-dev.autoload : invalid value, must be a string containing a version constraint...

Mixing

php

Set short_open_tag=On in php.ini And restart your Apache server...

show div only when printing

javascript,html,css

You need some css for that #printOnly { display : none; } @media print { #printOnly { display : block; } } ...

Cant submit form

javascript,php

Your PHP is checking if $_POST['submit'] contains a value. Your form does not contain a form element with the attribute name="submit", so therefore it fails and moves straight to the else statement. If you want to check if the form was posted then you should instead check for: if (!empty($_POST))...

access the json encoded object returned by php in jquery

php,jquery,ajax,json

Try: $.ajax({ url: "functions.php", dataType: "JSON", data: {id: id}, type: 'POST', success: function(json){ for(var i=0;i<json.length;i++){ alert(json[i].fname); } } }); ...

tag in HAML

html,css,haml

HAML equivalent is %i{class:"fa fa-search"} You can look at http://codepen.io/anon/pen/BNwbEP and see the compiled view ...

array and function php

php,arrays

$x and $y are only defined within the scope of the function. The code outside of the function does not know what $x or $y are and therefore will not print them. Simply declare them outside of the function as well, like so: <?php function sum($x, $y) { $z =...

Why am getting this error?: Unknown column 'firstname' in 'field list'

php,database,mysqli

$query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, $firstname, $lastname,$username,$password)"; you need single quote around text feilds in sql queries change above query to $query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, '$firstname', '$lastname','$username','$password')"; ...

Automatically calling server side class without

javascript,html,ajax

Trigger the click event like this: $('._repLikeMore').trigger('click'); ...

How to remove all the borders of a selectbox?

jquery,html,css,drop-down-menu

Firefox has some problems with select-background. You can try this code - it'll remove the arrow, and then you can add a background image with your arrow (I took an icon from google search, just put you icon instead) I get this on FireFox (You can use any arrow icon...

Error connecting to MSSQL using PHP

php,sql-server,pdo,odbc,sqlsrv

Change it to: $this->link = new PDO( "sqlsrv:Server={$this->serverName},{$this->port};Database={$this->db};", $this->uid, $this->pwd ); The default SQL Server port is 1433. Note the curly brackets, they allow for class variables....

Time format conversion with PHP

php,time

<?php $duration="1H10M5S"; $display=str_replace(array('H','M','S'), array(' Hour(s) ',' Minute(s) ',' Seconds'), $duration); echo $display; Output 1 Hour(s) 10 Minute(s) 5 Seconds Fiddle...

why i don't get return value javascript

javascript,jquery,html,json,html5

the first "A" in AJAX stands for "Asynchronous" that means, it is not executed right after it has been called. So you never get the value. Maybe you could first, get the os list and then output what you need, like this: function createCheckBoxPlatform(myDatas) { $.ajax({ url: "/QRCNew/GetOS", type: "post",...

How to search images by name inside a folder?

php,mysql,image

This looks like a job for glob, which returns an array of file names matching a specified pattern. I'm aware of the other answer just posted, but let's provide an alternative to regex. According to the top comment on the docs page, what you could do is something like this:...

Get elements containing text from array

javascript,jquery,html,arrays,contains

You can use :contains selector. I think you meant either one of those values, in that case var arr = ['bat', 'ball']; var selectors = arr.map(function(val) { return ':contains(' + val + ')' }); var $lis = $('ul li').filter(selectors.join()); $lis.css('color', 'red') <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li>cricket bat</li> <li>tennis ball</li> <li>golf ball</li>...

CSS :hover that shows more than one image

html,css,css3

Okay so I have got a probable solution, the catch is, you won't be able to use img tags. You can use images as background-image and animate background on :hover NOTE: Fade in effect can be removed by playing with animation. HTML <div class="image-box"></div> CSS .image-box { height: 200px; width:...

submitting form then showing loading image by javascript

javascript,html

Let suppose on button click you are calling ajax method <button onclick="LoadData();"/> before ajax call show image and onComplete ajax method hide this image function LoadData(){ $("#loading-image").show(); $.ajax({ url: yourURL, cache: false, success: function(html){ $("Your div id").append(html); }, complete: function(){ $("#loading-image").hide(); } }); } ...

how to multiply two column names using codeigniter validation rule

php,codeigniter,validation

You done need to do anything with your controller. Add this change your view to <script> function calculate() { var myBox1 = document.getElementById('crop_quantity').value; var myBox2 = document.getElementById('per_rate').value; var result = document.getElementById('income_amount'); var myResult = myBox1 * myBox2; result.value = myResult; } window.onload = calculate(); </script> <div class="control-group"> <label class="control-label">Crop Quantity</label>...

MySQL Query returning strange values

php,mysql

You need to join by account_id and also question_id SELECT * FROM `quiz_questions` INNER JOIN `quiz_answers` ON `quiz_questions`.`account_id` = `quiz_answers`.`account_id` AND `quiz_questions`.`question_id` = `quiz_answers`.`question_id` WHERE `quiz_questions`.`account_id` = '1840979156127491' ORDER BY `quiz_questions`.`question_id` ASC LIMIT 5 ...

How to register global variable for my Laravel application?

php,laravel,laravel-5

Actually, you should reserve in config/app.php file. Then, you can add In the Service Providers array : 'Menu\MenuServiceProvider', In the aliases array : 'Menu' => 'Menu\Menu', Finally, you need to run the following command; php artisan dump-autoload I assume that you already added this package in composer.json Sorry, I didn't...

How to pass a value from a page to another page in PHP

php

Only values that are sent by a form will be in the GET or POST array. From what you are showing I conclude that you don't want to show the field in your form, so make it hidden. Add this inside your form tag: <input name="price" type="hidden" value="'.$price.'" class="inputClass"> Also,...

php include capitalization on files

php

Your local host must be Windows, that doesn't differentiate between upper and lower case in file names and your web server Unix Based which does, simple as that.

php redirection working in chorme but not on firefox

php,google-chrome,mozilla

have you tried using header('location') function? example : <?php if (isset($_POST['putonline'])) { $query = "UPDATE user SET status= '1' WHERE id= '$new_id'"; $result = $cid-> query($query); if ($result== TRUE) { header("location:EidEmp.php"); die(); } else { echo "Failed"; } } ?> Edited : Maybe Change Your header function with javascript function...

Laravel 4.2 Sending email error

php,email,laravel,laravel-4

Closures work just like a regular function. You need to inject your outer scope variables into function's scope. Mail::send('invoices.mail', array($pinvoices,$unpinvoices), function($message) use ($email) { $message->to($email , 'Name')->subject('your invoices '); }); ...

Detect when the jQuery UI slider is being moved?

jquery,html,css,jquery-ui

You can use 3-Events: - Start (Start-Sliding) -> Stop Player - End (End-Sliding) -> Start Player - Slide (Sliding) -> Move Player-Position $("#range").slider({ range: "min", start: function(event, ui) { player.pauseVideo(); }, stop: function(event, ui) { player.playVideo(); }, slide: function(event, ui) { player.seekTo(ui.value,true); return false; } }); Demo: http://codepen.io/anon/pen/EjwMGV...

Website showing differently in windows xp and mobile

html,css

The background colour changes when the browser width is less than 1200px wide. You have specified the background-color for the selector .td-grid-wrap within a media query: What you need to do is move the background-color property to the non-media-queried selector .td-grid-wrap or perhaps .td-page-wrap. ...

PHP Regular Expressions Counting starting consonants in a string

php,regex

This is one way to do it, using preg_match: $string ="SomeStringExample"; preg_match('/^[b-df-hj-np-tv-z]*/i', $string, $matches); $count = strlen($matches[0]); The regular expression matches zero or more (*) case-insensitive (/i) consonants [b-df-hj-np-tv-z] at the beginning (^) of the string and stores the matched content in the $matches array. Then it's just a matter...

Div with the form of a pencil [duplicate]

html,css,css-shapes

.pencil{ width: 200px; height: 40px; border: 1px solid #000; position: relative; } .pencil:before{ content: ''; display: block; margin: 10px 0; width: 100%; height: 10px; border: 6px solid #000; border-width: 6px 0; } .pencil:after{ content: ''; display: block; height: 10px; border: 1px solid #000; border-width: 1px 1px 0 0; width:...

How to remove unmatched row in html table using jquery

jquery,html

Try this solution: var notrem = []; $('#Table1 tr').each(function(){ var currentRowHTML = $(this).find("td:first").html(); $('#Table2 tr').each(function(i){ var c= $(this).find("td:first").html(); if(c == currentRowHTML ){ notrem.push(i); } }); }); $('#Table2 tr').each(function(i){ if(notrem.indexOf(i) < 0){ $(this).remove(); } }); Explanation: First gather all indexes of Table2 that are equal and are not to be removed....

RecursiveIteratorIterator to fetch subdirectories

php

I would change if ( $dir->isDir() ) to if ( $dir->isDir() && $dir != $root) to remove the root directory...

How can I replace the white rectangle within an image using ImageMagick?

php,image-processing,imagemagick

I think you can locate the shape pretty accurately with a simple threshold, like this: convert image.jpg -threshold 90% result.jpg and you can then do a Canny edge detection like this: convert image.jpg -threshold 90% -canny 0x1+10%+30% result.jpg The next things I would be looking at are, using the -trim...

Symfony 2 unable to pass entity repository to form

php,forms,symfony2,runtime-error

You have not included the Symfony EnityRepository class at the top of your form file so PHP is looking for it in the same directory as your form class. Hence the error message. Add this to your form class (or qualify EntityRepository inline): use Doctrine\ORM\EntityRepository; ...

How do I display my mysql table column headers in my php/html output?

php,html,mysql,table,data

Note: You can just make a single file out of it to achieve your wanted output Use mysql_real_escape_string() to sanitize the passed-on value to prevent SQL injections You should use mysqli_* instead of the deprecated mysql_* API Form them in a single file like this (display.php): <html> <form method="post" name="display"...

PHP / MySQLi: How to prevent SQL injection on INSERT (code partially working)

php,mysql,mysqli,sql-injection,sql-insert

In the New PHP code snippet, you are still vulnerable to injections. You are using a prepared statement in the insert part, but you are not actually using the preparations strengths correctly. When creating a prepared statement, you create a query in which you add placeholders instead of the raw...

Target next instance of an element/div

javascript,jquery,html

nextAll and first: $(this).nextAll('.hidden').first().slideToggle(...); This question has more about this: Efficient, concise way to find next matching sibling?...

Dynamically resize side-by-side images with different dimensions to the same height

javascript,html,css,image

If it's responsive, use percentage heights and widths: html { height: 100%; width: 100%; } body { height: 100%; width: 100%; margin: 0; padding: 0; } div.container { width: 100%; height: 100%; white-space: nowrap; } div.container img { max-height: 100%; } <div class="container"> <img src="http://i.imgur.com/g0XwGQp.jpg" /> <img src="http://i.imgur.com/sFNj4bs.jpg" /> </div>...

How to make background body overlay when use twitter-bootstrap popover?

html,css,twitter-bootstrap

Posting some more code would be nice. This should work. Use some jQuery or AngularJs or any other framework to make the .overlay initially hidden, then to make it visible when needed. If you need help, comment. If it helps, +1. EDIT $(function() { $('[data-toggle="popover"]').popover({ placement: 'bottom' }); $("#buttonright").click(function() {...

change css dynamically by selecting dropdown list item

jquery,html,css,drop-down-menu

I have created a working example for you. You can find the jsfiddle in here This piece of code uses JQuery. (Remember, for these type of tasks, JQuery is your friend =] ). HTML <select id="dropDownMenu"> <option value="option1" selected="selected">yes</option> <option value="option2">no</option> </select> <br> <img id="picture" src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/House_Sparrow_mar08.jpg/220px-House_Sparrow_mar08.jpg"> Javascript function changeStyle(){...

Click on link next link should be display on same page

javascript,php,jquery,html,css3

Ok, so i tried to decypher what you meant with your Question. To Clarify: He has this one page setup. inside the div Our Project, there are two Buttons or links Visit more. When clicked, he wants the About Section to be shown. All in all it is impossible for...

Top header 100% of screen, but body only 70%?

html,css

Put your header inside the body. And don't apply styles to the body but use a container. + You should have one single header in your page. <body> <header> <nav><ul> <li class="active"><a href="#">Home</a></li> <li><a href="#">Solutions & Services</a> <ul> <li><a href="#">Internet</a></li> <li><a href="#">Networking</a></li> <li><a href="#">Website</a></li> <li><a href="#">Home...

Dynamically select from a dynamically generated dropdown

php,html,select,drop-down-menu

It is because you aren't ending the value attribute, so your selected option becomes <option value="optionvalueselected" -- 'optionvalue' being the value of your selected option, and 'selected' being the attribute you want to set, but won't be set because you never ended value The following should work: <select name="course_id" id="course_id">...