Brief:
Based on a query, I have multiple checkboxes generated dynamically. The value of each checkbox is a string from one of the query's rows;
upon form submission, another script is ran (del.php). This script gets the array of checkboxes that were checked and loops through them so it can ran another two queries, which is the delete and update queries.
They don't work! if I try the INSERT query, it works fine. But the DELETE AND UPDATE don't.
Here is my code:
index.php:
<?php
$gettips = mysql_query('SELECT body FROM tips WHERE body!="" and approved!="yes" and approved!="no"')or die(mysql_error());
$i=0;
while($tips = mysql_fetch_array($gettips))
{ ?>
<input type="checkbox" name="checkboxes[]" value="<?php print $tips[0] ?>" />
<input type="checkbox" name="checkboxesno[]" value="<?php print $tips[0] ?>" />
<a class="names"> - <span><?php print $tips[0] ?></span></a><br />
<? $i++;
}
?>
and del.php :
foreach($_POST['checkboxes'] as $check) {
mysql_query("INSERT INTO approved (body) VALUES ('$check') ");
mysql_query("UPDATE tips SET approved='yes' WHERE body='$check'");
}
foreach($_POST['checkboxesno'] as $key) {
mysql_query("DELETE FROM tips WHERE body='$key' ")or die(mysql_error());
}
mysql_error() doesn't throw any errors. Database connection works in both files. The values of the checkboxes are strings. I'm able to delete the record by adding the string itself rather than the POST $variable to the query.
(I have also noticed that I'm not able to delete older records, only the newly added ones).
UPDATE:
I realized that trying to delete records where row='string' wasn't the best practice, at least in my case. So, instead of passing strings as values to the checkboxes in the form, I decided to give the id value of the table.
here is the new code:
<?php
$gettips = mysql_query('SELECT id,body FROM tips WHERE body!="" and approved!="yes" and approved!="no"')or die(mysql_error());
$i=0;
while($tips = mysql_fetch_array($gettips))
{ ?>
<input type="checkbox" name="checkboxes[]" value="<?php print $tips[0] ?>" />
<input type="checkbox" name="checkboxesno[]" value="<?php print $tips[0] ?>" />
<a class="names"> - <span><?php print $tips[1] ?></span></a><br />
<? $i++;
}
?>
and the delete queries:
foreach($_POST['checkboxes'] as $check) {
// echo "INSERT INTO approved (body) VALUES ('$check') <br>";
// echo "UPDATE tips SET approved='yes' WHERE body='$check'<br>";
mysql_query("INSERT INTO approved (body) VALUES ('$check') ");
mysql_query("UPDATE tips SET approved='yes' WHERE body='$check'");
}
foreach($_POST['checkboxesno'] as $key) {
// echo "DELETE FROM tips WHERE id=$key <br>";
mysql_query("UPDATE tips SET approved='no' WHERE id=$key");
mysql_query("DELETE FROM tips WHERE id=$key ")or die(mysql_error());
}
I still don't know why the other way wasn't working, so if someone out there has a chance to explain, it would be awesome!
If you add some echo statements to your forloops and comment out the queries, you'll be able to see what exactly is being sent to mysql, and then you'll be better able to solve your problem.
foreach($_POST['checkboxes'] as $check) {
echo "INSERT INTO approved (body) VALUES ('$check') <br>";
echo "UPDATE tips SET approved='yes' WHERE body='$check'<br>";
//mysql_query("INSERT INTO approved (body) VALUES ('$check') ");
//mysql_query("UPDATE tips SET approved='yes' WHERE body='$check'");
}
foreach($_POST['checkboxesno'] as $key) {
echo "DELETE FROM tips WHERE body='$key' <br>";
//mysql_query("DELETE FROM tips WHERE body='$key' ")or die(mysql_error());
}
Try and protect yourself from SQL Injections: http://php.net/manual/en/security.database.sql-injection.php, can you please output the exact generated SQL query, it may be because of the SQL string not escaped.
Try escaping it with mysql_real_escape_string();
Related
I've researched this for two days and just about have it working... trouble is, when I check TWO checkboxes on my dynamically populated form, I get FOUR records inserted. It gets weirder... ONE of the records is unique. THREE have the same information. I'm totally lost here.
Here is the code for the form:
<form name="form1" id="form1" method="post" action="insert_zip_codes.php?u=<?php echo $_SESSION['username'] ?>">
<table class="bordered" cellspacing="0">
<tr><th>City</th><th>State</th><th>ZIP Code</th></tr>
<?php while($row = mysql_fetch_array($rs)) { ?>
<tr><td><input name="zip_code[]" type="checkbox" id="zip_code" value="<?php echo $row[zip_code] ?>" /></td><td><?php echo $row[city] ?></td><td><?php echo $row[state] ?></td><td><?php echo $row[zip_code]?></td></tr>
<?php } ?>
</table><br />
<input type="submit" name="Submit" value="Submit" />
</form>
Here is the code for the insert statement on the next page.
<?php $u = $_GET['u']; ?>
<?php var_dump($_REQUEST); ?> </br> </br>`
<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
mysql_query($query);
}
if(mysql_query($query))
{
echo 'success';
}
else
{
echo 'failure' .mysql_error();
}
echo $query; // print the sql to screen for de-bugging
$results = mysql_query($query); ?>
When I hit submit, the following prints out and it inserts successfully into the database.
["zip_code"]=> array(2) { [0]=> string(5) "97477" [1]=> string(5) "97478" }
Looks right, right? But then the database gets these records...
id 40 username *** zip_code 97478
id 41 username *** zip_code 97478
id 42 username *** zip_code 97478
id 43 username *** zip_code 97477
As you can see, the darned thing is entering the first zipcode checked on the page only once (as the fourth record) but is entering the SECOND zipcode first THREE TIMES.
Any idea why? I'm at a loss.
Thank you in advance!!! :)
You are calling mysql_query() 3 times, and with 2 of them outside your foreach() loop, it will insert the last $query/$zip_code an additional 2 times.
<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
mysql_query($query); // 1st time (does query foreach zip_code)
}
if(mysql_query($query)) // 2nd time (does query on last zip_code a second time)
{
echo 'success';
}
else
{
echo 'failure' .mysql_error();
}
echo $query; // print the sql to screen for de-bugging
$results = mysql_query($query); // 3rd time (does query on last zip_code a third time) ?>
Removing the last one, as it is just there for de-bugging, you could change your loop code to -
<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
$result = mysql_query($query);
if($result)
{
echo 'success ';
}
else
{
echo 'failure' .mysql_error();
}
}
The problem relates to your use of mysql_query() and the $query variable you are using.
Here's a walk through.
You submit two postcodes via $_POST
You loop through the $_POST array and set $query to be the INSERT string.
You then pass that into the function mysql_query() to execute the command to INSERT the record.
So now, you've got two records in your database. You didn't do any checks to see if they worked individually as inserts during that loop (you should have). You also didn't do any escaping to avoid dodgy injection tampering. (you should have).
Anyway, after your loop, this is where it all goes wrong. You then check to see if it worked by running mysql_query($query) again. This is actually going to run the last $query INSERT string you generated again as a command. So that inserts another record into the table.
THEN, you do something with the variable $results by yet again, running the mysql_query($query) command. So that's another record you've inserted.
This means you would have 4 records inserted into your table.
A suggestion
This is off the top of my head! - not tested it
$u = "Whatever";
$inserted = 0;
$fatal = Array();
foreach($_POST['zip_code'] AS $z){
if(mysql_query("INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".mysql_real_escape_string($z)."')";
$success += mysql_affected_rows();
} else {
$fatal[] = mysql_error();
}
}
echo "Inserted $success of ".count($_POST[zip_code])." records.<br />";
if(count($fatal)){
$fatal = array_unique($fatal);
echo "The following error(s) occurred:<br />";
print "<pre>";
print_r($fatal);
print "</pre>";
}
Hope that helps in some way!
I am having issues getting information out of mysql into multiple checkboxes.
The query im using is this.
<?php
$usergroupid = $_SESSION['UserGroupID'];
$sql="SELECT * FROM sites WHERE UserGroupID='{$usergroupid}' ORDER BY sites.Description";
$result=mysql_query($sql);
while ($row=mysql_fetch_array($result))
$description=$row["sites.Description"];
{
?>
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $description; ?>">
<?php
}
?>
but this only inputs 1 checkbox and has no text after it when there are multiple rows in the table.
Well for starters, never use the same id twice in HTML (you go through a for loop and make each element have the same id, not a good thing). Fix that issue first (make the HTML input element's id include some kind of id from the row)
Then, the real problem comes from the fact that you put the
$description=$row["sites.Description"];
line before your opening brace for the while statement. It should be
while ($row=mysql_fetch_array($result))
{
$description=$row["sites.Description"];
instead.
I would change the code to:
<?php
$usergroupid = $_SESSION['UserGroupID'];
$sql="SELECT * FROM sites WHERE UserGroupID='{$usergroupid}' ORDER BY sites.Description";
$result=mysql_query($sql);
while ($row=mysql_fetch_array($result))
{
$description=$row["sites.Description"];
?>
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $description; ?>">
<?php
}
?>
The problem was that the "{" should've been written directly after "while ($row=mysql_fetch_array($result))".
Also, I would strongly recommend stop using mysql_query if possible, since mysql_query is now deprecated (read more about it here: http://php.net/manual/en/function.mysql-query.php).
It's not the only issue your code has. For example the formatting, I mean you can't really read it. Learn to properly format your code, sort it up. That will actually help you to prevent other errors.
And as commented, it will also help you to read and understand your code.
And now as the third tip: If you ask a question with properly formatted code you will also get better answers here on the website. So please keep your issues important and do all the best you can do to get help here on site.
<?php
$usergroupid = $_SESSION['UserGroupID'];
$sql = sprintf(
"SELECT * FROM sites WHERE UserGroupID = %d ORDER BY sites.Description",
(int)$usergroupid
);
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$description = $row["sites.Description"];
echo '<input name="checkbox[]" type="checkbox" id="checkbox[]" value="',
$description, '">';
}
You should use mysqli extension instead mysql(is deprecated)
$sql="SELECT * FROM sites WHERE UserGroupID='{$usergroupid}' ORDER BY sites.Description";
$i=0;
$result=mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result)){
$description=$row["sites.Description"];
$xxx= "<input name='checkbox[]' type='checkbox' id='checkbox_$i' value='$description'>";
$i++;
}
echo $xxx;
?>
$description have to be inside the while.
id="checkbox_$i Add autoincrement to make diferent the ids
So as said in title I'm trying to use the query variable given from the page which directs to this one and the form data from THIS page to manipulate the database. I can't seem to get it right and I have no idea what I'm doing wrong. The code snippet looks like this:
<?php
$ware_number = $_GET['id'];
Echo "<form action='usernamecheck.php' method='post'>";
Echo 'Username:<br>';
Echo '<input type="text" name="usernamecheck" size="14"><br>';
Echo 'Password:<br>';
Echo '<input type="password" name="passwordcheck" size="14"><br>';
Echo '<input type="submit" value="Send">';
Echo '</form>';
if (isset($_POST['usernamecheck'])) {
$sql2 = "SELECT * FROM `storedata`.`users` WHERE `username` LIKE '$_POST[usernamecheck]'";
$found_user_id = mysql_query($sql2, $conn);
print $found_user_id;
}
if (isset($_POST['usernamecheck'])) {
$sql3 = "INSERT INTO `storedata`.`basket` (user_id, ware_id, number, complete)
VALUES
('$found_user_id', '$ware_number', 1, 0)";
$derp = mysql_query($sql3, $conn);
print $derp;
}
?>
The document itself is usernamecheck.php, and I was just printing to try and locate the error. When i check the basket table nothing has happened, even though no error is displayed. Right now the variable $ware_number is causing errors. What am I doing wrong?
I have also made user_id and ware_id foreign keys in the storedata.basket table, since they are primary keys in their own respective table. This means they can only be specific values, but I'm testing with these values, primarily 1's and 0's...
What if $_GET['id'] is not set? it will fail. Also please read up into correct usage of SQL in PHP. Your code is vulnerable to SQL injection attacks and whatnot.
EDIT:
updated piece of code
if(isset$_GET['id'] && is_numeric($_GET['id']))
{
$ware_number = $_GET['id'];
Echo "<form action='usernamecheck.php?id=" . $_GET['id'] . "' method='post'>";
.....
i have this code which permits me to do a request in order to make a query!
Now the form which is processed has this code:
<form action="edit_images.php" method="post">
<input type="hidden" value="<? echo $gal_id1 ?>" name="img_id1" />
<input type="submit" value="Edit All Images" />
</form>
While the query is like this :
$img_id=$_REQUEST['img_id1'];
$sql="SELECT * FROM tbl_images WHERE Img_gal_id='$img_id'";
But it seems like it won't take the value...
I mean, it doesn't recognize the $img_id, which i have printed before and takes the exact value.
Let me show you the query i use in order to retrieve it:
$sql = "SELECT gal_id,gal_title,gal_image FROM tbl_galleries where gal_id='" . $_REQUEST['gid'] ."';";
$query = mysql_query($sql) or $myErrorsP = mysql_error();
if(isset($myErrors) && $myErrorsP!=''){
} else {
$row = mysql_fetch_row($query);
mysql_free_result($query);
$gal_id = $row[0];
$gal_id1 = $row[0];
$gal_title = $row[1];
$gal_image = $row[2];
}
You are missing a ; on the end of your echo that isn't outputting the value as expected. Additionally, you are using short tags, which could be causing problems. You might want to swtich to using <?php as an opening over <? on it's own.
<input type="hidden" value="<?php echo $gal_id1; ?>" name="img_id1" />
Lastly, you are using zero protection against injection attacks. Please, research prepared statements in PDO and update your code. The first injection attack you don't have will thank you for it.
Edit: When you run into a problem like this, it is often good practice to echo out the $sql just before you execute it.
you could do this in the future with:
$sql = "SELECT gal_id,gal_title,gal_image FROM tbl_galleries where gal_id='" . $_REQUEST['gid'] ."';";
echo $sql."<br>\n";
$query = mysql_query($sql) or $myErrorsP = mysql_error();
which would have probably given you an excellent indication of what the problem was.
I'm VERY new to MySQL and PHP and have been teaching myself for sometime. I'm not expecting anyone to write my code for me, but I am looking for some suggestions on how best to proceed with this script.
I have a set of users that can update their "skill level" on a particular set of products. At the moment, I have all that working. However, I don't want the user to have to update every skill level each time they submit.
So, in other words, I want them to be able to leave a field blank, but populate other fields with their skill level, thus only updating the fields they have input.
I'm doing this all on a dev server so here is my code that I'm currently working with.
mysql_connect("127.0.0.1","root","time2start") or die("Connection Failed");
mysql_select_db("joomla_dev_15") or die ("Database Connection Failed");
$user = $_POST['user'];
$USP = $_POST['USP'];
$USPV = $_POST['USPV'];
$VSP = $_POST['VSP'];
echo "$user<br />";
echo "$USP<br />";
echo "$USPV<br />";
echo "$VSP<br />";
$query = "UPDATE `joomla_dev_15`.`enterprise_storage` SET `$user` = '$USP' WHERE `enterprise_storage`.`id` = 1;";
if(mysql_query($query))
{
echo "updated<br />";
}else{
echo "FAILURE";
}
$query = "UPDATE `joomla_dev_15`.`enterprise_storage` SET `$user` = '$USPV' WHERE `enterprise_storage`.`id` =2;";
if(mysql_query($query))
{
echo "updated<br />";
}else{
echo "FAILURE";
}
$query = "UPDATE `joomla_dev_15`.`enterprise_storage` SET `$user` = '$VSP' WHERE `enterprise_storage`.`id` =3;";
if( mysql_query($query) )
{
echo "updated<br />";
}else{
echo "FAILURE";
}
Any help or suggestions would be greatly appreciated!
Maybe I'm not understanding this fully, but checking you variables before the UPDATE statement should be enough.
$user = $_POST['user'];
$USP = $_POST['USP']; // Make sure to escape this
if (!empty(trim($USP))) { // Added a trim so that when space is entered, it will still be considered empty
$query = "UPDATE `joomla_dev_15`.`enterprise_storage` SET `$user` = '$USP' WHERE `enterprise_storage`.`id` = 1;";
if(mysql_query($query))
{
echo "updated<br />";
}else{
echo "FAILURE";
}
}
else {
echo "Empty String. Nothing to Do"
}
I was able to figure it out in a way that was satisfactory for me.
Keep in mind, that this code is not necessarily sanitized or secure from malicious attacks, this is simply a dev server so I could prove the concept, and I WILL come back later and secure it.
Also, I've taught myself, so this is most likely not the most efficient way to do this
In order to get the current default values of the user's skills, I had to run this query
$result = mysql_query("SELECT id , user FROM enterprise_storage WHERE id =1");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row1 = mysql_fetch_array($result);
This allowed me to assign a variable to each row that was returned based on this specific query. So, in this case, the person (named "user" in this example) would return a skill level for Product ID "1"
Once I ran this same query for the few items I wanted to assign variables, I could then place this in my html form as the default value for each text box:
Please enter your skill level on the following products:</br>
USP: <input type="text" name="USP" value=<?php echo $row1[user]?> /><br />
USPV: <input type="text" name="USPV" value=<?php echo $row2[user]?> /><br />
VSP: <input type="text" name="VSP" value=<?php echo $row3[user]?> /><br />
I've omitted the rest of the HTML, because its not relevant right now.
In the end, this solves my problem as it places a default value into the form field, and thus the user doesn't need to update that value if they don't want to.
Thanks for all the suggestions!
Check if the form values are blank and do not post them into the database if they are - also, you really need to look at cleansing user input before putting it into the database. See http://php.net/manual/en/function.mysql-real-escape-string.php for example.