[Solved] Undefined Index inside a While PHP


The field “candidateid” should be integer data type, but you are enclosed this field value with ”(single quotes) in the update query?

$sql = "UPDATE candidate_info SET numberofvotes = 1 WHERE candidateid = '$candidateid'";

if it is an integer datatype then you should remove the single quote

$sql = "UPDATE candidate_info SET numberofvotes = 1 WHERE candidateid = $candidateid";

and in MySQL every field names are case sensitive, so as you told the field names are

candidateid, candidatename, position, numberofvotes

so, you should use these names when you retrieving the values as well

    <?php
             if(isset($_POST['update'])) {
                $dbhost="localhost";
                $dbuser="root";
                $dbpass="";
                $candidateid = $_POST['candidateid'];
                $conn = mysql_connect($dbhost, $dbuser, $dbpass);

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

                $candidateid = $_POST['candidateid'];


                $sql = "UPDATE candidate_info SET numberofvotes = numberofvotes + 1 WHERE candidateid = '$candidateid'" ;
                mysql_select_db('election2016');
                $retval = mysql_query( $sql, $conn );

                if(! $retval ) {
                   die('Could not update data: ' . mysql_error());
                }
                echo "Updated data successfully\n";

                mysql_close($conn);
             }
    ?>
<html>
    <center>
    <font size="2" face = "century gothic">
    <?php
    $con=mysqli_connect("localhost","root","","election2016");
    // Check connection
    if (mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $result = mysqli_query($con,"SELECT * FROM candidate_info");
    ?>
    <form method = "post" action = "<?php $_PHP_SELF ?>">
    <?php
    echo "<table border="1">
    <tr>
    <th>Candidate Name</th>
    <th>Position</th>
    <th>Vote</th>
    <th>Number of Votes</th>
    </tr>";
    while ($row = mysqli_fetch_array($result)) {
        echo "<tr>";
        echo "<td>" . $row['candidatename'] . "</td>";
        echo "<td>" . $row['position'] . "</td>";
        echo "<td><input type="radio" name="candidateid" value="".$row["candidateid']."' >";
        echo "<td>" . $row['numberofvotes'] . "</td>";
    }
    echo "</table>";
    mysqli_close($con);
    ?>

    <br>
    <br>
    <input name = "update" type = "submit" id = "update" value = "update">
    </form>
    </center>
    </font>
    </html>

16

solved Undefined Index inside a While PHP