Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 3 123 LastLast
Results 1 to 15 of 35
  1. #1
    New Coder
    Join Date
    May 2012
    Posts
    20
    Thanks
    6
    Thanked 0 Times in 0 Posts

    PHP Multiple Checkbox[Duplicate Values inserted]

    Good Evening Coding forums,
    i have been checking out your tutorials for checkboxes for my Project Student Elections as those who had the same problem as i am currently facing but with no solution

    To give you a brief explaination of my issue is :
    Step 1: I retrieve Candidate ID from Table 'Candidates' and insert them into a checkbox
    Step 2 : Student selects the number of candidates for example 5 [since i only have 5 currently inserted]
    Step 3 : It inserts the selected values into another table of the database [Table : Votes]

    the issue i am having is the "For Loop" if i select for example : 157 ,158 , 160 and 161

    it inserts duplicates of one value as in 157
    i have stressed myself to get it work and need experts help

    Note : Vardump and Counter gives a real proof that selected values are from the checkbox

    This is the code :
    PHP Code:
    <?php
    session_start
    ();
    $submit=$_POST['submit'];
    echo 
    "Please Vote for the following Candidates: ";
    echo 
    "<br>";
    echo 
    "<br>";

    if(
    $_SESSION['student_id']){
    echo 
    "Welcome,".$_SESSION['student_id']."!<br><a href='logout.php'>Log out</a>";
    $studentID=$_SESSION['student_id'];


    $connect=mysql_connect(*********","*********","*********");
    mysql_select_db("
    *********");
    $candidate=mysql_query("
    Select Candidate_ID from candidates");
    echo "
    <form action ='' method='post'>";
    while($row=mysql_fetch_assoc($candidate))
    {
    echo "
    Candidate ".$row['Candidate_ID']." <input type='checkbox' name='Candidates[]' value='".$row['Candidate_ID']."'><br>";

    echo "
    <br>";
    }

    echo "
    <input type='submit' name='submit' value='Vote' /></form>";

    if($submit){

    if(!empty($_POST['Candidates']))
    {

    //counter=0;


    //Loops to get all 4 values


    foreach($_POST['Candidates'] as $voters )
    {
    //Checks if array of 5 candidates exists
    var_dump($_POST['Candidates']);
    //Checks if selected value is outputted
    $voters=implode(',',$_POST['Candidates']);
    echo "
    <br>";
    echo "
    <br>";
    echo "
    Checks if selected valeus are outputted using implode".$voters;
    echo "
    <br>";
    echo "
    <br>";
    echo "
    Using Counter to check if it outputs";
    echo "
    <br>";
    for($i=0;$i<$voters;$i++)
    {

    echo $voters[$i];
    }
    //Connecting to Database
    $connect=mysql_connect("
    *****.***************","******","********");
    mysql_select_db("
    ********");
    //insert this vote into DB
    $query = "
    INSERT INTO votes (student_id,candidate_id)
    Values('$studentID','$voters')";
    //If table not found this error will show
    mysql_query($query) or die('Error, query failed');
    die("
    <br>**Your votes has been saved**</br><br><a href='logout.php'>Click here to log out</a>");
    echo "
    <br>";

    }





    }
    else
    {
    echo "
    <br>";
    echo "
    <b>**You have not selected candidates</b>";
    echo "
    <br>";
    }
    }
    }

    ?>
    Last edited by Salman1990; 05-28-2012 at 06:39 PM.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    I'm not sure what you are attempting to do within that foreach. $voters is in use, is overwritten as a string, then iterated which will be successful for the (int) cast of the $voters string.
    This is also not a very good idea structurally. Since this is a many to many relationship, you should be using a database to flatten the many relationships to one, not inserting a comma separated field into the database. Since this is a voting type system, doing a comma separated value is particularly bad since you now rely on the language to do the processing instead of allowing the SQL to aggregate the data. You have it half right here, but its still not right. You are iterating each result and inserting, but you are inserting a comma separated field that is the same every time.

    What's the value of var_dump($_POST['Candidates']);? What's the parsed HTML for that form as well?

  • #3
    New Coder
    Join Date
    May 2012
    Posts
    20
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Ah my bad those in the "For Loop" i was messing around with the code and found out that it outputs "Implode" and "Counter" i am including the attachment
    as shown in Screenshot 1
    "Vardump shows the array()"

    I know that implode is a very bad idea to store them into the database since its containing a comma plus i am storing Integers not varchars

    This code is without the "implode and counter" hope its understandable now

    PHP Code:
    <?php

    session_start
    ();
    $submit=$_POST['submit'];
    echo 
    "Please Vote for the following Candidates: ";
    echo 
    "<br>";
    echo 
    "<br>";

    if(
    $_SESSION['student_id']){
    echo 
    "Welcome,".$_SESSION['student_id']."!<br><a href='logout.php'>Log out</a>";
    $studentID=$_SESSION['student_id'];


    $connect=mysql_connect("mysql12.***************","a6790551_root","goofy45sora");
    mysql_select_db("a6790551_elect");
    $candidate=mysql_query("Select Candidate_ID from candidates");
    echo 
    "<form action ='' method='post'>";
    while(
    $row=mysql_fetch_assoc($candidate))
    {
    echo 
    "Candidate ".$row['Candidate_ID']." <input type='checkbox' name='Candidates[]' value='".$row['Candidate_ID']."'><br>";

    echo 
    "<br>";
    }

    echo 
    "<input type='submit' name='submit' value='Vote' /></form>";

    if(
    $submit){

    if(!empty(
    $_POST['Candidates']))
    {

    //counter=0;


    //Loops to get all 4 values


    foreach($_POST['Candidates'] as $voters )
    {
    //Connecting to Database
    $connect=mysql_connect("mysql12.***************","a6790551_root","goofy45sora");
    mysql_select_db("a6790551_elect");
    //insert this vote into DB
    $query "INSERT INTO votes (student_id,candidate_id)
    Values('$studentID','$voters')"
    ;
    //If table not found this error will show
    mysql_query($query) or die('Error, query failed');
    die(
    "<br>**Your votes has been saved**</br><br><a href='logout.php'>Click here to log out</a>");
    echo 
    "<br>";

    }





    }
    else
    {
    echo 
    "<br>";
    echo 
    "<b>**You have not selected candidates</b>";
    echo 
    "<br>";
    }
    }
    }

    ?>
    Attached Thumbnails Attached Thumbnails PHP Multiple Checkbox[Duplicate Values inserted]-screenshot-1.png  
    Last edited by Salman1990; 05-28-2012 at 08:57 PM.

  • #4
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    This is better yeah.
    This looks fine, the array you have is only the two values checked (presumably the 157 and 158). These should be the only two options inserted into the database.

    This still needs modification though, in particular that loop with the querying. Opening and closing a connection isn't a good idea, and inserting multiples can be factored down to a single insertion in a single table.
    PHP Code:
    if (isset($_POST['Candidates']) && count($_POST['Candidates']) > 0)
    $connect mysql_connect(...);
    ...
    $sQry 'INSERT INTO votes (student_id, candidate_id) VALUES ';
    $aValues = array();
    foreach (
    $_POST['Candidates'] AS $vote)
    {
        
    $aValues[] = "('$studentID', '$vote')";
    }
    if (!empty(
    $aValues))
    {
         
    $sQry .= implode(', '$aValues);
    }
    mysql_query($sQry) or die('Error, insertion failed.'); 
    I'm not seeing anything in the screenshot indicating duplicate entries. If you are referring to duplicates in the database, you will need to issue a select first, or run through a REPLACE, INSERT ON CONFLICT, etc. If both of these fields are a composite primary key, it can be ignored since it will fail to insert a duplicate.

  • Users who have thanked Fou-Lu for this post:

    Salman1990 (05-28-2012)

  • #5
    New Coder
    Join Date
    May 2012
    Posts
    20
    Thanks
    6
    Thanked 0 Times in 0 Posts
    I removed the duplication part before submitting the previous post:

    the code below I made it like this by inserting 4 extra values thinking that i didnt add extra rows to be inserted or so ....

    PHP Code:
    //insert this vote into DB
    $query "INSERT INTO votes (student_id,candidate_id)
    Values('$studentID','$voters'),('$studentID','$voters'),('$studentID','$voters')
    ,('$studentID','$voters')"

    I have a compensate Key

    Vote ID - Is an auto increment , Student ID and Candidate ID are a foreign key as shown in Screenshot 2
    Attached Thumbnails Attached Thumbnails PHP Multiple Checkbox[Duplicate Values inserted]-screenshot-2.jpg  

  • #6
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    You have to choose one of two options with the structure. You can keep the voteID if you decide its necessary, convert both the student_id and candidate_id into non-nullable fields (you really shouldn't have anything with null tbh), and most importantly flag them as a composite UNIQUE KEY (should be easy to do in phpmyadmin as well; I typically use the cli for database work, but it must be composite). The other option is to drop the voteID completely and make a composite primary of the student_id and candidate_id (this is what I'd do as I typically avoid surrogates as much as possible). Overall the structure is correct though.
    Never do this:
    PHP Code:
    $query "INSERT INTO votes (student_id,candidate_id)
    Values('$studentID','$voters'),('$studentID','$voters'),('$studentID','$voters')
    ,('$studentID','$voters')"

    You don't know what is available for $voters, so don't hardcode the multiple insertions. The code I have above will create a dynamic string of this same type of representation only based off of the candidates checked.

    Edit:
    BTW, if you have MySQLi as an option, you'd be better using the prepared statements of the mysqli library and binding the execution than to use an insertion like above. I didn't do anything with security either, but you would need to cast them:
    Code:
        $aValues[] = "(" . (int)$studentID . ", " . (int)$vote . ")";
    Last edited by Fou-Lu; 05-28-2012 at 09:30 PM.

  • Users who have thanked Fou-Lu for this post:

    Salman1990 (05-28-2012)

  • #7
    New Coder
    Join Date
    May 2012
    Posts
    20
    Thanks
    6
    Thanked 0 Times in 0 Posts
    The thing is the student has to select 16 candidates and 8 should be from both gender the issue if i removed the Vote ID will i be able to secure completely the voting phase making the student who logs again not able to vote again and then i have to publish these results by counting the number of Candidate IDs selected and post the results of the winners

    and your previous post of the modifications includes the connection of the database and inside the loop?

    i am not sure if i understand but the implode you just made it will output for example : 157,158,159,160
    do i need a substring to remove the comma ???
    Last edited by Salman1990; 05-28-2012 at 09:42 PM.

  • #8
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    No, the connection isn't in the loop. And no the result of the implode won't be the numbers comma separated. It will be (111, 157), (111, 158)[, ....] for the results. Used for the insert and multiple entries. Binding would be my recommended route if its available for use.

    The surrogate key is never required. If it is, there is something wrong with the structure when identifying a primary key. Its most used for shortcuts like here on the forums, the thread has an id associated with it, but there will be a usable unique entry to identify it otherwise (user, date, title, etc). So rather than have showthread.php?user=123&date=1788889339&title=the%20title its just easier to use a surrogate. Same applies to the voteid, its not actually required but may be easier to use (I can't tell you either way since I'm not writing the code that will affect it). You can still develop any COUNT() you need with the groups, as a surrogate is useless to group on anyway.

    Now as for selections, you need some additional logic for that. Simple queries that lookup and count the number of male/female based from the IN result of the checked id's. So long as you end up with a count of each (group by gender) that match your rules, then you can go ahead and insert.

  • Users who have thanked Fou-Lu for this post:

    Salman1990 (05-28-2012)

  • #9
    New Coder
    Join Date
    May 2012
    Posts
    20
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Well I quite understand now and learned about surrogate need further knowledge on this I would like to thank you for your time and will be testing the code that you have modified and post the results
    Your work is appreciated
    Thanks Again
    Hope for expected results

  • #10
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Yep you bet. Come back if you have any more questions

  • #11
    New Coder
    Join Date
    May 2012
    Posts
    20
    Thanks
    6
    Thanked 0 Times in 0 Posts
    i would like to thank you again , the code that you have modified is working and successfully enters all the checkbox values selected
    i would like to keep this post open if i have any possible errors in the future

  • #12
    New Coder
    Join Date
    May 2012
    Posts
    20
    Thanks
    6
    Thanked 0 Times in 0 Posts
    hey there i would like to ask a simple question
    is storing an image a good idea in mysql or not?

    the possible way to retrieve it from mysql
    is having A blob , a photo type and the name i have tried doing all those sent the type to the header it keeps on giving me a message containing file errors

    This is how i am currently getting the image


    PHP Code:
    $image=mysql_query("Select * from candidates where Student_ID='$studentID'");
    while(
    $row=mysql_fetch_assoc($image))
    {
    $type="Content-type: ".$row['Candidate_Photo_Type'];
    header($type);
    echo 
    $row['Candidate_Photo_File_Content'];

    Last edited by Salman1990; 06-05-2012 at 10:12 PM.

  • #13
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    That should work if you are storing it in a blob field type, have the proper header and it only issues one result from the query. You can take out the header to see the binary as well, but if its issuing an error its either due to bad data in the first place, or its due to an error in the code that's issuing an output notice, warning etc to the client. That's all interpreted as a part of the image too.

    IMO for the most part a filesystem is superior to using a DBMS for image data. There are pros and cons to using either, but typically speaking if you are in doubt then the filesystem wins. Its faster, images are served in a way you don't have to do anything to interpret them, and tend to put less load on the process. Conversely, DBMS directly have a better granularity into the access privileges, and you can carry them around you easily with little effort. Tradeoffs are part and parcel with programming.

  • #14
    New Coder
    Join Date
    May 2012
    Posts
    20
    Thanks
    6
    Thanked 0 Times in 0 Posts
    i have tried removing the header before it gives me all binary data

  • #15
    New Coder
    Join Date
    May 2012
    Posts
    20
    Thanks
    6
    Thanked 0 Times in 0 Posts
    I have got the image to work by seperating it from the candidate profile.php and inserting to a php page called 'image.php'

    The issue now i am facing is i would like to put this code into the candidateprofile.php to display the image and all contents of that candidate it gives me image contains error files whenever i insert the header is it because of session_start()?

    PHP Code:
    ?php

    $link 
    mysql_connect(*******', '******', '******');
    @mysql_select_db('
    *******',$link);
    $sql = "SELECT * FROM candidates WHERE Student_ID = 20090130;";

    $result = mysql_query($sql) or die(mysql_error());  
    $row = mysql_fetch_array($result);

    header("Content-type: image/jpeg");
    echo $row['
    Candidate_Photo_File_Content]; 

    ?> 


  •  
    Page 1 of 3 123 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •