Hello i am trying to make a trade script were users can trade each others monsters.
So i have a script were it shows there monsters and the users monsters that they type in so if the user types in nick it will shows the pokemon nick monsters and the user who typed it in monster.
All of whic works fine it displays what i want.
Now i want to store the monsters they want and are offering in the db. And that is were we come to the problem. For some resosn its storing the username and the username of the trader ok but not the monsters. Its storing
{"pokemon":[""]}
For the trade_pokeid and the trade_mypokeid
Here is how i display there monsters and the users monsters which works fine
Trade with </h4>
<?php
$username_trade = $_POST['username_trade'];
$_SESSION['username_trade'] = $username_trade ;
echo "You put in id ". $username_trade . ".<br />";
?>
</p>
<p> </p>
<p><span class="mid_box">
<?php
// get and display userbox
$q = "SELECT id,pokemon,exp,level FROM user_pokemon WHERE belongsto='". $_SESSION['username_trade']."'";
$r = mysql_query($q);
if (mysql_num_rows($r) <= 0) {
echo "You have no current pokemon stored";
}
?>
</span></p>
<p> </p>
<p>
<?php
echo "<form action='test_process.php' method='POST'>";
while ( $v = mysql_fetch_object( $r ) )
{
echo "<label><input type='checkbox' name='pokemon[]' value='$v->dbid'/> They have a $v->pokemon </label><br/>";
echo "<label> Level $v->level </label><br/>";
}
echo "<input type='hidden' name='user' value='$username_trade'/>";
echo "<input type='submit' value='Check!!'/>";
?>
</p>
<p><strong>Pick what you want two offer for the pokemon </strong></p>
<p>
<?php
// get and display userbox
$q = "SELECT id,pokemon,exp,level FROM user_pokemon WHERE belongsto='". $_SESSION['username']."'";
$t = mysql_query($q);
if (mysql_num_rows($t) <= 0) {
echo "You have no current pokemon stored";
}
?>
</p>
<p>
<?php
echo "<form action='test_process.php' method='POST'>";
while ( $v = mysql_fetch_object( $t ) )
{
echo "<label><input type='checkbox' name='pokemonin[]' value='$v->dbid'/> I have a $v->pokemon</label><br/>";
echo "<label> Level $v->level </label><br/>";
}
echo "<input type='hidden' name='userin' value='$username'/>";
echo "</form>";
?>
<p align="center">
Now here is how i try and store them.
<?php
include 'config.php';
$pokemon = $_POST['pokemon'];
$pokemonin = $_POST['pokemonin'];
$meid = $_SESSION['username'];
$toid = $_POST['user'];
$dbid = array();
$dbid2 = array();
foreach ( $pokemon as $poke )
{ $dbid['pokemon'][] = $poke;
}
foreach ( $pokemonin as $poke2 )
{ $dbid2['pokemonin'][] = $poke2;
}
srand ((double) microtime( )*1000000);
$random_number = rand( );
echo "$random_number";
mysql_query("INSERT INTO trade (trade_id, trade_to, trade_from, trade_pokeid, trade_mypokeid)
VALUES ('$random_number','$toid', '$meid', '"$dbid."', '".$dbid2."');") or die("Error: ". mysql_error());
?>
What am i doing wrong ? why are the results not being stored ? or carried over the db connect and session start are in the config.php page
In your last MySQL query, you're trying to insert a PHP array as a string into a query, that won't work. If I'm guessing correctly, you'll want to use something like implode(",",$dbid['pokemon']) instead of $dbid.
Also, it's definitely a good idea to run mysql_real_escape_string on anything that comes from the user and/or the URL before you put it in a query!
Your code is open for sql injection !
You shuld aviod passing parameters (without escaping) to sql query => for start check:
http://php.net/manual/en/function.mysql-real-escape-string.php
You have an error (not enough - or too many dots) in your MYSQL statement...
VALUES ('$random_number','$toid', '$meid', '"$dbid."', '".$dbid2."')
Should read
VALUES ('$random_number','$toid', '$meid', '$dbid', '$dbid2')
Related
I am creating an SIC code lookup and I am having a weird issue with my query. I have 6 table names, description, description-2, description-3. and two-digit-sic, four-digit-sic, and six-digit-sic and I am getting unexpected results.
If I search for an item in any of the description tables (example: agriculture) it will return the correct queries. and it will display as it should. As well as if I only search for a two-digit-sic. (example: 01)
However if I try and search via six-digit-sic or four-digit-sic It will not display the records.
A weird thing is when I search for the correct six-digit-sic it will say it found records but just not display them. if you put in an incorrect sic code it will just say no records found. example of working six-digit-sic (011198) non-working SIC (112112)
I am truly at a loss as to why this is happening.
this is live here: http://mainstaycomputing.com/client/prospects/list-brokers-resources/sic-code-search/
<?php
get_header();
?>
<div id="main-content" style = 'position: relative'>
<div class = 'wrapper'>
<h1 class="entry-title main_title"><?php the_title(); ?></h1>
<div class = 'sic-text'>
<p> SIC codes are assigned by the Government and are standard at the 4 digit level.
The 8 digit codes may be customized by each individual list owner. Because we represent all list
sources, there may be variance in what the 8 digit codes represent. For greatest accuracy,
when speaking with one of our List Brokers please supply the sic code # along with a description so
we can provide as exact a match as possible.To use this search, simply type the Industry you’re
looking for into the Search By Keyword field. For instance, entering “Dentists” will cause all
businesses related to dentists listed. <! — If you know the SIC code and want to know the industry
name, enter the 8 digit code into the Search By Code field. –> </p>
</div>
<form action="" method="GET" class = 'sic-search'>
<input class = 'sic-search-text' type="text" name="search" placeholder="Search for an industry, eg 'Agriculture'"/>
<input type="submit" value="Search" class = 'sic-search-button'/>
</form>
<?php
$search = $_POST['search'];
$host = "****";
$user = "****";
$password = "****";
$database_name = "****";
$min_length = 2;
// you can set minimum length of the sic if you want
if(strlen($search) >= $min_length && $search != ''){ // if sic length is more or equal minimum length then
echo "<p id='rowCount'> </p>";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
// Search from MySQL database table
$search=$_POST['search'];
$query = $pdo->prepare("select * from siccodes where description LIKE ? OR description-2 LIKE ?");
$query->bindValue(2, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table class='sic-code-table'";
echo "<tr><th>description</th><th>two-digit-sic</th><th>description</th><th>four-digit-sic</th><th>description</th><th>six-digit-sic</th></tr>";
while ($results = $query->fetch()) {
echo "<tr><td>";
echo $results['description'];
echo "</td><td>";
echo $results['two-digit-sic'];
echo "</td><td>";
echo $results['description-2'];
echo "</td><td>";
echo $results['four-digit-sic'];
echo "</td><td>";
echo $results['description-3'];
echo "</td><td>";
echo $results['six-digit-sic'];
echo "</tr>";
}
echo "</table>";
} else {
echo "<p style = 'text-align:center; margin-bottom:30px; color: red;'>No results match" . " '" . $search . "' " . "Please try another search term.</p>";
}
} else {
if (!empty($_POST['search'])) {
echo "<p style = 'text-align:center; margin-bottom:30px; color: red;'> Please search again, '$search' is to short.</p>";
}
}
$host = "****";
$user = "***";
$password = "***!";
$database_name = "*****";
mysql_connect("****", "****", "****") or die("Error connecting to database: ".mysql_error());
/*
localhost - it's location of the mysql server, usually localhost
root - your username
third is your password
if connection fails it will stop loading the page and display an error
*/
mysql_select_db("****") or die(mysql_error());
/* tutorial_search is the name of database we've created */
?>
<?php
$query = $_GET['search'];
// gets value sent over search form
// if the query is null which it would be when they first enter the page then show all results
if(empty($_GET['search'])) {
// $query = '01';
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM siccodes ") or die(mysql_error());
// * means that it selects all fields, you can also write: `id`, `title`, `text `
// articles is the name of our table
// '%$query%' is what we're looking for, % means anything, for example if $query is Hello
// it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
// or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
echo "<table class='sic-code-table'";
echo "<tr><th>description</th><th>two-digit-sic</th><th>description</th><th>four-digit-sic</th><th>description</th><th>six-digit-sic</th></tr>";
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<tr><td>";
echo $results['description'];
echo "</td><td>";
echo $results['two-digit-sic'];
echo "</td><td>";
echo $results['description-2'];
echo "</td><td>";
echo $results['four-digit-sic'];
echo "</td><td>";
echo $results['description-3'];
echo "</td><td>";
echo $results['six-digit-sic'];
echo "</tr>";
// posts results gotten from database(title and text) you can also show id ($results['description'])
}
echo "</table>";
}
} // end of displaying all results
/* this is the actual search */
$min_length = 2;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM siccodes
WHERE (`description` LIKE '%".$query."%') OR (`description-2` LIKE '%".$query."%') OR (`description-3` LIKE '%".$query."%') OR (`two-digit-sic` = '$query') OR (`four-digit-sic` = '$query') OR (`six-digit-sic` = '$query')") or die(mysql_error());
// * means that it selects all fields, you can also write: `id`, `title`, `text `
// articles is the name of our table
// '%$query%' is what we're looking for, % means anything, for example if $query is Hello
// it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
// or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
$raw_num_rows = mysql_num_rows($raw_results);
$num_rows = $raw_num_rows - 1;
echo "<p id='rowCount'> We have retrieved " . " " . $num_rows . " " . " records related to the keyword '$query'</p>";
echo "<table class='sic-code-table'";
echo "<tr><th>description</th><th>two-digit-sic</th><th>description</th><th>four-digit-sic</th><th>description</th><th>six-digit-sic</th></tr>";
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<tr><td>";
echo $results['description'];
echo "</td><td>";
echo $results['two-digit-sic'];
echo "</td><td>";
echo $results['description-2'];
echo "</td><td>";
echo $results['four-digit-sic'];
echo "</td><td>";
echo $results['description-3'];
echo "</td><td>";
echo $results['six-digit-sic'];
echo "</tr>";
// posts results gotten from database(title and text) you can also show id ($results['description'])
}
echo "</table>";
}
else{ // if there is no matching rows do following
echo "<p style='text-align:center;color:red;'>No results for '$query' | Please try again";
}
}
else{ // if query length is less than minimum
echo "<p style='color:orange; text-align:center; '>Minimum length is ".$min_length."</p>";
}
?>
<!-- creates a form at the bottom of the list if there are more than 100 records -->
<?php if(mysql_num_rows($raw_results) > 100) : ?>
<form action="" method="GET" class = 'sic-search'>
<input class = 'sic-search-text' type="text" name="sic" placeholder="Search for an industry, eg 'Agriculture'"/>
<input type="submit" value="Search" class = 'sic-search-button'/>
</form>
<?php endif; ?>
</div> <!-- end of wrapper -->
</script>
</div> <!-- #main-content -->
<?php get_footer(); ?>
I have two php page.
In the first I have looping checkbox array :
<td><input type="checkbox" name="cek[]" value=" <?php echo "$kodeinventarisit" ?>"></td>`
Then i submit form from page one to page two :
<?php
include 'koneksi.php';
$cek = $_POST['cek'];
$jumlah_dipilih = count($cek);
for($x=0;$x<$jumlah_dipilih;$x++){
$jojo = $cek[$x];
$coba = "select * from msstok where kodeinventarisit = '$jojo' ";
$cobaquery = mysql_query($coba);
$hasil = mysql_fetch_array($cobaquery);
$jenis = $hasil['jenis'];
?>
<input name="kode" type="text" id="license" value="<?php echo htmlentities($jenis) ; ?>" readonly="readonly" />
<?php
echo "$jojo";
}
?>
The problem is in the sql query return nothing, I try echo "$jojo" and it's print the value but in the text field is empty..
Does anyone have suggestions on how to fix this?
Thank You Very Much
1
What you are doing is bad.
Load your data before your loop and loop every result to print them.
2
Protect your sql request from injection.
Connect
$db = new mysqli("","root","","");
Prepare your request
$sql = "select * from msstok where kodeinventarisit = ? ";
$res = $db->prepare($sql);
$res->bind_param("sssd",$jojo);
Get results
$res->execute();
Documentation : http://php.net/manual/fr/book.mysql.php
If you want to pass the array you need to check if arrive in you second page.
<pre>
print_r($_POST['cek']);
</pre>
Now, if arrive here, you can read the values like this:
<?php
// If is array(), then you can go to loop
if(is_array($_POST['cek']))
{
// Run the loop
foreach($_POST['cek'] as $value)
{
// Show values per line
echo $value. "<br/>";
}
}
?>
You can read only 1 value of your array
<?php echo $_POST['cek'][0]; ?>
<?php echo $_POST['cek'][1]; ?>
<?php echo $_POST['cek'][2]; ?>
Conclusion
You can't pass array to SQL in query. If you want to use it, this is the only way with implode.
$coba = "SELECT * FROM msstok WHERE kodeinventarisit IN (".implode(',', $jojo).")";
$records = mysql_query($coba, $connection);
while ($row = mysql_fetch_array($records)) {
echo "Name: " . $rows['name'] . "<br />"; // replace the name for column you want
}
This is my first php project. I have created a website where users can upload their picture and then view the pictures of other users, one person at a time (similar to the old hotornot.com). The code below works as follows:
I create an array (called $allusers) containing all members except for the user who is currently logged in ($user).
I create an array (called $usersiviewed) of all members who $user has previously either liked (stored in the likeprofile table) or disliked (stored in the dislikeprofile table). The first column of likeprofile and dislikeprofile has the name of users who did the liking/disliking, second column contains the name of the member they liked/disliked.
I use the array_diff to strip out $usersiviewed from $allusers. This is the list of users who $user can view (ie, people they have not already liked or disliked in the past).
Now the problem is when I click the like button, it updates the likeprofile table with the name of the NEXT person in the array (i.e., not the person who's picture I am currently looking at but person who's picture appears next). Additionally, if I refresh the current page, the person who's profile appears on the current page automatically gets 'liked' by me. I would really appreciate any advice on this.
<?php
// viewprofiles.php
include_once("header.php");
echo $user.' is currently logged in<br><br>';
echo <<<_END
<form method="post" action="viewprofiles.php"><pre>
<input type="submit" name ="choice" value="LIKE" />
<input type="submit" name ="choice" value="NEXT PROFILE" />
</pre></form>
_END;
$allusers = array();
//Create the $allusers array, comprised of all users except me
$result = queryMysql("SELECT * FROM members");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
if ($row[0] == $user) continue;
$allusers[$j] = $row[0];
}
//Create the $i_like_these_users array, comprised of all users i liked
$result = queryMysql("SELECT * FROM likeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_like_these_users[$j] = $row[1];
}
//Create the $i_dislike_these_users array, comprised of all users i disliked
$result = queryMysql("SELECT * FROM dislikeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_dislike_these_users[$j] = $row[1];
}
//Create the $usersiviewed array, comprised of all users i have either liked or disliked
if (is_array($i_like_these_users) && is_array($i_dislike_these_users))
{
$usersiviewed = array_merge($i_like_these_users,$i_dislike_these_users);
}
elseif(is_array($i_like_these_users))
{
$usersiviewed = $i_like_these_users;
}
else
{
$usersiviewed = $i_dislike_these_users;
}
// this removes from the array $allusers (i.e., profiles i can view) all $usersviewed (i.e., all the profiles i have already either liked/disliked)
if (is_array($usersiviewed))
{
$peopleicanview = array_diff($allusers, $usersiviewed);
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
else {
$peopleicanview = $allusers;
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
$current_user_profile = $peopleicanview[0];
echo 'check out '.$current_user_profile.'s picture <br />';
if (file_exists("$current_user_profile.jpg"))
{echo "<img src='$current_user_profile.jpg' align='left' />";}
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['choice']) && $_POST['choice'] == 'LIKE')
{
$ilike = $current_user_profile;
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$ilike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['choice']) && $_POST['choice'] == 'NEXT PROFILE')
{
$idontlike = $current_user_profile;
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$idontlike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
?>
Because when you refresh page it sends previus value of
Form again...and problem when u like a user it being liked next user.. There there is something in yor for loop while fetching row ...insted of for loop try once while loop ...i hope it will solve ur problem
You are calculating the $iLike variable with the currently loaded user and then updating the database with that user.
You should probably change your application logic a bit:
pass the user ID of the user you liked or did not like as a POST parameter in addition to the like/didn't like variable
move the form processing logic to the top of your page (or better yet separate out your form processing from HTML display)
Also, it's best not to use the mysql_* extensions in PHP. Use mysqli or PDO.
Try to make two different forms. One with "LIKE", another with "NEXT" to avoid liking from the same form
When you submit your form - your page refreshes, so in string $current_user_profile = $peopleicanview[0]; array $peopleicanview doesn't have user from previuos page (before submitting) you have to attach it, e.g. in hidden field
<form method="post" action="viewprofiles.php">
<input type="hidden" name="current_user" value="$current_user_profile" />
<input type="submit" name ="choice" value="like" />
</form>
<form method="post" action="viewprofiles.php">
<input type="submit" name ="go" value="next" />
</form>
and INSERT it later
"INSERT INTO likeprofile VALUES" . "('$user', '".$_POST['current_user']."')"
ps remove <pre> from your form
Lets start by simplifying and organizing the code.
<?php
// viewprofiles.php
include_once("header.php");
//if form is sent, process the vote.
//Do this first so that the user voted on wont be in results later(view same user again)
//use the user from hidden form field, see below
$userToVoteOn = isset($_POST['user-to-vote-on']) ? $_POST['user-to-vote-on'] : '';
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['like']))
{
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['dislike']))
{
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
//now we can create array of available users.
$currentProfileUser = array();
//Create the $currentProfileUser array,contains data for next user.
//join the 2 other tables here to save php processing later.
$result = queryMysql("SELECT `user` FROM `members`
WHERE `user` NOT IN(SELECT * FROM `likeprofile` WHERE user='$user')
AND `user` NOT IN(SELECT * FROM `dislikeprofile` WHERE user='$user')
and `user` <> '$user'
LIMIT 1");
//no need for a counter or loop, you only need the first result.
if(mysql_num_rows > 0)
{
$row = mysql_fetch_assoc($result);
$current_user_profile = $row['user'];
}
else
$current_user_profile = false;
echo $user.' is currently logged in<br><br>';
//make sure you have a user
if($current_user_profile !== false): ?>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="like" value="LIKE" />
</form>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="dislike" value="NEXT PROFILE" />
</form>
check out <?=$current_user_profile?>'s picture <br />
<?php if (file_exists("$current_user_profile.jpg")): ?>
<img src='<?=$current_user_profile.jpg?>' align='left' />
<?php endif; //end check if image exists ?>
<?php else: //no users found ?>
Sorry, there are no new users to view
<?php endif; //end check if users exists. ?>
You'll notice I changed the code a lot. The order you were checking the vote was the main reason for the issue. But over complicating the code makes it very difficult to see what's happening and why. Make an effort to organize your code in the order you expect them to run rather a vote is cast or not, I also made an effort to separate the markup from the logic. This makes for less of a mess of code to dig through when looking for the bug.
I also used sub queries in the original query to avoid a bunch of unnecessary php code. You could easily have used JOIN with the same outcome, but I think this is a clearer representation of what's happening. Also please use mysqli instead of the deprecaded mysql in the future, and be aware of SQL injection attacks and makes use of real_escape_string at the very least.
Hope it works out for you. Also I didn't test this code. Might be a few errors.
http://i.stack.imgur.com/Gy3o0.png
That is what the site looks like now. What I want to do is when you click on the approve registration on the table, it will extract the value of the id no and the name of that particular record. I thought i was on the right track. I knew how to get the id no. But it doesn't get the value of the name at the same time.
This is how the code looks like:
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr>";
echo "<td><form method=post action=approvedmayor.php><input type='radio' name=id value='$id'></td>";
}
approvedmayor.php
$query = mysql_query("insert into tbcandidates VALUES ($id, '$name', 'mayor')");
if ($query)
{
echo "You appproved ";
echo $name;
}
else
echo "error";
you can try like this...
<?php
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr><td><a href='approvedmayor.php?id=$id&name=$name'>Approve</a></td></tr>";
}
?>
in this type don't use the form, and Approve button... try this alone
Actually it is bad practice to insert that kind of data directly from POST data.
If you have all these candidates already stored in the database, you should run a SELECT query in your approvedmayor.php first, and if the candidate still exists, insert it's data to another table.
$query = mysql_query('SELECT * FROM `candidates` WHERE `id` = '.$id.' LIMIT 1');
if(mysql_num_rows($query)) {
$candidate = mysql_fetch_assoc($query);
$insertQuery = mysql_query("insert into tbcandidates VALUES ($candidate['id'], $candidate['name'], $candidate['mayor'])");
if ($insertQuery) {
echo "You appproved ";
echo $name;
} else echo "error";
} else echo 'This candidate is no longer available';
I understand your question,
But thats not the best way go ahead, Before we move let us understand some little elements functions
Radio Button : Its an input type element, that allows the user to choose only one [ 1 ] of option given list.
Check Boxes : Its an input type element, that allows the user to select n number of options or selections from give list.
Fore info - http://www.w3schools.com/html/html_forms.asp
Now comming to your question..
You need to modify your code to check boxes as below
<input type='checkbox' name=id[] value='$id'>
Notice : elements name is in Array mode.. ie whenever a user one or more than one, the values are stored in array.
Once the values are stored in array, call it / use if however you want.
For your mentioned code
echo "<form method=post action=approvedmayor.php>';
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr>";
echo "<td><input type='radio' name=id[] value='$id'></td>";
}
echo "</form>";
approvedmayor.php
$temp_app_arr = $_POST['id'];
foreach ($temp_app_arr as $pos => $val) {
$query = mysql_query("insert into tbcandidates VALUES ('$val', '$name', 'mayor')");
if ($query) {
echo "You appproved ";
echo $name;
} else {
echo "error";
}
}
And i believe this should gonna be good code / algorithm for your project.
I have a php form with some textbox and checkboxes which is connected to a database
I want to enter all the details into the database from the form.All the textbox values are getting entered except the checkbox values.I have a single column in my table for entering the checkbox values and the column name is URLID.I want to enter all the selected checkbox(URLID)values to that single column only ,separated by commas.I have attached the codings used.can anyone find the error and correct me?
NOTE: (The URLID values in the form is brought from the previous php page.those codings are also included.need not care about it)
URLID[]:
<BR><?php
$query = "SELECT URLID FROM webmeasurements";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
$URLID = $row[0];
echo "<input type=\"checkbox\" name=\"checkbox_URLID[]\" value=\"$row[0]\" />$row[0]<br />";
$checkbox_values = implode(',', $_POST['checkbox_URLID[]']);
}
?>
$URLID='';
if(isset($_POST['URLID']))
{
foreach ($_POST['URLID'] as $statename)
{
$URLID=implode(',',$statename)
}
}
$q="insert into table (URLID) values ($URLID)";
You really should separate your model from the view. It's 2011, not 2004 ;o
if (isset($_POST['checkbox_URLID']))
{
// Notice the lack of '[]' here.
$checkbox_values = implode(',', $_POST['checkbox_URLID']);
}
$URLIDs = array();
while($row = mysql_fetch_row($result))
{
$URLIDs[] = $row[0];
}
foreach ($URLIDs as $id)
{
?>
<input type="checkbox" name="checkbox_URLID[]" value="<?php echo $id; ?>" /><?php echo $id; ?><br />
<?php
}
?>
<input type="submit"/>