Inserting Data from dropdown into database with PHP - php

First I needed a dropdown list that I could update easily so I created a database called
manufacturers where I list manufacturers to be selected in a form.
I finally accomplished this with this code:
<?php
// Connect to the test datbase on localhost
// That's where we created the countries table above
mysql_connect('localhost','##user##','##pass##'); mysql_select_db('wordpress');
// Query the countries table and load all of the records
// into an array.
$sql = 'select * FROM manufacturers';
$res = mysql_query($sql) or die(mysql_error());
while ($rec = mysql_fetch_assoc($res))
$manufacturers[] = $rec;
?>
<form action="select.php" method="post">
<?php
echo '<select name="dropdown">';
foreach ($manufacturers as $c)
{
if ($c['id'] == $_GET['id'])
echo "<option value=\"{$c['meta_id']}\" selected=\"selected\">{$c['meta_value']} </option>\n";
else
echo "<option value=\"{$c['meta_id']}\">{$c['meta_value']}</option>\n";
}
echo '</select>';
?>
<input type="submit" value="Submit" name="submit"/>
</form>
This worked out great I now have a dropdown list that is populated from my
database manufacturers.
Now I need to send this to an existing database call post_meta so that from there I can display the users selection permanently.
I have tried a couple of different options but I am trying to use the following code to send this to my post_meta database.
<?php
$con = mysql_connect("localhost","##user##","##pass##");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wordpress", $con);
$sql="INSERT INTO wp_postmeta (meta_id, post_id, meta_key, meta_value)
VALUES
('$_POST['meta_id']}','$_POST[post_id]','$_POST[meta_key]','$_POST[meta_value]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
This actually inserts into the database but doesn't record any values.
Please help me figure out what I'm doing wrong.

The proper way to do this is to A: escape all those $_POST superglobals.
and B. Write a query as shown below.
Here's the tabledef for wp_postmeta:
http://codex.wordpress.org/Database_Description#Table:_wp_postmeta
Because meta_id is an auto_increment primary key, you do not provide it, MySQL does.
//$meta_id = mysql_real_escape_string($_POST['meta_id']); <<-- not needed.
$post_id = mysql_real_escape_string($_POST['post_id']);
$meta_key = mysql_real_escape_string($_POST['meta_key']);
$meta_value = mysql_real_escape_string($_POST['meta_value']);
$sql=" INSERT INTO wp_postmeta
(post_id, meta_key, meta_value)
VALUES
('$post_id','$meta_key','$meta_value') "; //<<-- don't forget the quotes!
if ($result = mysql_query($sql)) {
//You can get the new meta_id using:
$new_meta_id = mysql_insert_id($result);
} else {
die ("could not insert ".mysql_error());
}

Do none of your values show up? It looks like you're missing quotes around your key values. For example, shouldn't it be :
$_POST['post_id']
To do a sanity check, just echo your $_POST variables as opposed to doing the insert right away. This will help you figure out if you've got some syntax wrong. Also I'd read Brad's comment and keep it in mind for the future.

Try this query:
$sql="
INSERT INTO wp_postmeta
(meta_id, post_id, meta_key, meta_value)
VALUES
(
'{$_POST['meta_id']}',
'{$_POST['post_id']}',
'{$_POST['meta_key']}',
'{$_POST['meta_value']}'
)
";
And, as people say in comments, this code is very vulnerable, please consider to find better option to pass variables into query.

Related

how to make the value from the drop-down list remembered and entered into the database after the confirmation button?

I have a list code but it didn't get further)
<?
include("connect.phtml");
$r= mysql_query("SELECT name_goods FROM goods")
or die ("!1");
echo "<select name='product'>";
while($row=mysql_fetch_array($r))
{
echo "<option value='".$row['name_goods']."'>".$row['name_goods']."</option>";
}
mysql_close();
?>
You should put your name_goods id into your option value instead of the name.
Then you will need to insert a $_POST['product'] (which will be the selected value) to your database with the appropriated query.
Something like :
$good_id = $_POST['product']
$query = $pdo->prepare("INSERT INTO table(good_id) VALUES (".$good_id.")");
$query->execute();

Php checkboxes to rows

I need to insert each checkbox to row in MySql.
At the moment i am able to catch only one checkbox, but I usually have them 1 - ... who knows how many..
All my checkboxes come from Db like that :
<input type="checkbox" name="lisateenus[]" value="<?php echo $row["id"]; ?>">
On insert it should take the "page id" what is created and after that insert checkbox values to table.
it gets all needed ID-s but it inserts only one checkbox what is checked..
$result = mysqli_query($con,$query);
if($result) {
$last_id = $con->insert_id;
$error = "Uus Teenus lisatud! ". $last_id;
$checkBox = implode(',', $_REQUEST['lisateenus']);
$query="INSERT INTO lisateenuse_seos (p_id, l_id, lisaja) VALUES ($last_id,'" . $checkBox . "','1')";
mysqli_query($con, $query) or die (mysql_error() );
echo "Complete";
} else {
$error = "Teenuse lisamine ei õnnestunud";}
So everything is working exept that it only inserts one row, but 3 rows are checked and should be inserted..
"each checkbox has his own ID (different) only last_id and lisaja have the same id, so each checkbox should be separate row in MySql table (after insert)"
In that case, you actually don't want to implode your checkboxes, but go through with a foreach on them:
foreach ( $_REQUEST['lisateenus'] as $somevalue ) {
$query="INSERT INTO lisateenuse_seos (p_id, l_id, lisaja) VALUES ('$last_id' ,'" . $somevalue . "','1')";
mysqli_query($con, $query) or die (mysql_error() );
echo "Complete";
}
This should insert a new row for each checked checkbox. Using implode actually makes a single string from the whole array, which then you insert only once. With foreach, you send and insert command to the sql for each ( :D ) checked checkbox.
(I added some extra quotes for the good cause.)

2 for each statements at same time?

I recently have been trying to make a way to easily add more fields onto my form without having to go back and add more rows to my database structure. So, to begin working on this, I created a table where the structure is this:
OptionTitle
Option1
Option2
Option3
Option4
Option5
Option6
As you can see, it goes up to 6 options, and OptionTitle is the label name of the form. Then I made another table, one that reflects the users input of the previous table. This table is named usersoption
fid
OptionTitle
Option1
Ok, so FID reflects which form it is referencing to. This way, when displaying the submitted form, it'll pull information from this table where the FID is the same. OptionTitle is the label of the form, and Option1 is the option the user submitted.
Now, onto the form where it actually includes the options to select from. Here is a simplified version of how my code is included:
$query100 = $db->query("SELECT * FROM options WHERE fid='" . $id . "'");
while($row2 = mysqli_fetch_array($query100))
{
echo "
<div class=\"divform\" id=\"optiontitle\">
<label for=\"optiontitle\">$row2[optiontitle]:</label>
<select name=\"option1[]\" id=\"option1\">";
echo "<option value='$row6[option1]'>$row6[option1]</option>";
echo "<option value='$row6[option2]'>$row6[option2]</option>";
echo "<option value='$row6[option3]'>$row6[option3]</option>";
echo "<option value='$row6[option4]'>$row6[option4]</option>";
echo "<option value='$row6[option5]'>$row6[option5]</option>";
echo "<option value='$row6[option6]'>$row6[option6]</option>";
echo "
</select>
</div>
";
}
As you can see, the select name is option1[]. This is so I can have multiple select fields on the same form, and in return this will bring over the multiple difference select fields onto the submitted process. So now onto where my issue is, in the submission process. Here is what I have so far:
foreach($_POST['option1'] as $val){
$val = $db->escape_string($val);
$query30 = $db->query("INSERT `usersoption` SET `gid` = '".$id."', `fid` = '".$fid."', `optiontitle` = 'Where OptionTitle should go', `option1` = '$val'")or die( mysqli_error());
}
As you can see, I can successfully bring the option through a foreach statement. What I can't do, is bring in the OptionTitle. It seems almost unnecessary to bring in the OptionTitle, but it is necessary for the person reading the submitted form to know which option was being submitted. I'm not sure how to carry the OptionTitle over, it seems simple but all my attempts failed miserably. I did some research and one of the suggestions was to create a hidden input with the name and carry it over that way. Here is the addon that would be in the form:
<input type=\"hidden\" name=\"optiontitle[]\" value=\"test\">
This would be added on to the form and then carried over, but the issue is how do I bring it over? I would need to do a multiple foreach statement which does not work. For example, here was what I tried to bring over (it did not work):
foreach($_POST['option1'] as $val) && ($_POST['optiontitle'] as $val2)){
$val = $db->escape_string($val);
$val2 = $db->escape_string($val2);
$query30 = $db->query("INSERT `usersoption` SET `gid` = '".$id."', `fid` = '".$fid."', `optiontitle` = '$val2', `option1` = '$val'")or die( mysqli_error());
}
Have you tried giving your option array a key?
echo "<select name=\"option1[$row2[optiontitle]]\" id=\"option1\">";
Then change your foreach to:
foreach($_POST['option1'] as $title=>$val)
You can use key in foreach to access more array:
Try this code:
foreach($_POST['option1'] as $key=>$val){
$val = $db->escape_string($val);
$val2 = $db->escape_string(isset($_POST['optiontitle'][$key])?$_POST['optiontitle'][$key]:'');
$query30 = $db->query("INSERT `usersoption` SET `gid` = '".$id."', `fid` = '".$fid."', `optiontitle` = '$val2', `option1` = '$val'")or die( mysqli_error());
}
For the hidden input solution: Just do each query as you normally would, but add $_POST['optiontitle']:
foreach($_POST['option1'] as $val){
$val = $db->escape_string($val);
$query30 = $db->query("
INSERT `usersoption` SET
`gid` = '".$id."',
`fid` = '".$fid."',
`optiontitle` = '".$_POST['optiontitle']."',
`option1` = '$val'
")or die(mysqli_error());
}
By the way you should read up on prepared statements. These allow you to sanitise your data before inserting into the database. They are essential to good coding practise.

Can't check which check list is checked

I'm trying to delete multiple pictures using checkbox item. But somehow pictures are not deleted from database.
the coderuns without mistake. Page is being redirected but the delete query is not executed.
I believe there is somethong to do with passing picture id to query $List[1] but i really can't understand what.It seems I'm doing everything ok.
Thanks for any help in advance.
That's the code:
<?php
$Connection = mysql_connect( $Host, $User, $Pass ) or die('ERROR: '.mysql_error());
mysql_select_db( $DataBase )or die('ERROR: '.mysql_error());
$Query = "SELECT * FROM pictures WHERE folder_id = ".$FolId.";";
$Picture = mysql_query($Query, $Connection)or die('ERROR: '.mysql_error());
?>
<form name='Photos' method='POST' >
<?php
while($List = mysql_fetch_array($Picture)){
echo "<input type='checkbox' name='photoList[]' value='".$List[1]."'> <span> ".$List[4]."</span>";
}
?>
<input type='submit' name='Delit' value='DELETE' >
</form>
<?php
if(isset($_POST['Delit'])){
foreach($_POST['photoList'] as $item){
$Query="DELETE FROM pictures WHERE picture_id =".$item;
mysql_query($Query, $Connection)or die("ERROR: ".mysql_error());
header('Location: photos.php');
}
}
?>
My guess is that $List[1] doesn't contain your picture_id. It's probably $List[0].
Using fetch_array is not a great way to get data from a DB using SELECT *, as your columns may change position, and an index doesn't clearly say which column you're retrieving.
Try using fetch_assoc instead, to get the column names associated with the data.
<?php
// Change `picture_name` below to the name of the column storing your picture's name
while ($List = mysql_fetch_assoc($Picture)) {
echo "<input type='checkbox' name='photoList[]' value='{$List['picture_id']}'> <span> {$List['picture_name']}</span>";
}
?>
Also, try this for your DELETE logic:
Checking if photoList is set (vs. Delit)
Looping through your photo list and casting the values to (int) to prevent SQL Injection
Concatenating the list of IDs into a comma-delimited list using implode
Doing a DELETE... WHERE IN query, providing the photo ID list - this is much faster than looping through and doing several DELETE... WHERE = statements
Code:
<?php
if (isset($_POST['photoList']) && !empty($_POST['photoList'])) {
$photoIds = array();
foreach ($_POST['photoList'] as $photoId) {
$photoIds[] = (int) $photoId;
}
$photoIds = implode(',', $photoIds);
$Query = "DELETE FROM pictures WHERE picture_id IN ({$photoIds})";
mysql_query($Query, $Connection)or die("ERROR: ".mysql_error());
header('Location: photos.php');
}
?>

PHP and MySQL help needed

I have 2 tables in my database. categories and products. in categories there are 2 fields. catid and catname. and in products also there are 3 fields. id, catid and name.
in my submit form im fetching the catname in to a sector. what i wanna do is get value of the selector and save the catid in to products table catid field. instead of categories name. can anyone explain me how to do this. Thanks in advance.
Here is the code of submit form.
include("db.php");
$result = mysql_query("SELECT * FROM categories")
or die (mysql_error());
?>
<!--SubmitForm-->
<form method="post" action="add_products.php">
<select name="cat">
<?php
while($row = mysql_fetch_array($result))
{echo "<option value='".$row[catid]."'>".$row[catname]."</option>";}
?>
</select><br/>
<input type="text" name="name" value=""><br/>
<input type="submit" value="submit"/>
</form>
add_products.php Code
<?php
include("db.php");
$cat = $_POST['catid'];
$query = "SELECT * FROM categories WHERE catname='$cat'";
$result= mysql_query($query) or die ('Mysql Error');
while($row = mysql_fetch_array($result)){
$catn = $row['catid'];
}
$name = mysql_real_escape_string($_POST['name']);
$query="INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
?>
You already seem to have the right values, just need to put them in the correct spot, if you need the 'catid', you can just put it in the id tag of the select.
When you echo the you just need to do this,
echo "<option id='".$row[catid]."' value='".$row[cat]."'>".$row[catname]."</option>";
For more info refer to the w3school manual for , at this link.
Some unrelated, but very important things:
you should escape $cat before it goes into the query
you should always escape strings that go out to HTML with htmlspecialchars
you should always use $row['keyname'], not the deprecated $row[keyname]
Now for your question. The code seems correct on first glance, but I don't have PHP right now so I can't test it. Is there anything in particular that is not working as expected?
You already have it in??
$cat = $_POST['catid'];
If you only want to insert IF they $cat exists, then:
<?php
include("db.php");
$cat = $_POST['catid'];
$query = "SELECT * FROM categories WHERE catname='$cat'";
$result= mysql_query($query) or die ('Mysql Error');
if($result)
{
$name = mysql_real_escape_string($_POST['store']);
$query="INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
}
?>
You are already assigning the category ID to the category name in the select menu. The variable of the select menu is $_REQUEST['cat'], which holds the ID of the selected category after submitting the form. You can save this value directly to the product table.
However, the while loop in add_products.php is of no use, since you are always assigning the last ID in the table to the variable $catn. Replace this while loop with $catn = $_REQUEST['cat'] (while cat is the name of the select menu).
seem many mistakes here:
select name="cat"
and your try to receive $cat = $_POST['catid']; the correct is $cat = $_POST['cat'];
then you tries to select by catname
$query = "SELECT * FROM categories WHERE catname='$cat'";
when you need to compare ids catid='$cat'";
and what for to assign meny times if the result is single?:
if ( ($row = mysql_fetch_array($result)) ){
$catn = $row['catid'];
}
Your select field is names 'cat', so it should be $_POST['cat'] (or better, rename the select field to 'catid'). And it alreay contains the catid, so there's no need to get it from the DB again (unless you want to make sure it does in fact exist).
Finally, you should escape the $_POST['cat'] parameter as you do the name.
So this is sufficient:
$catid = mysql_real_escape_string($_POST['cat']);
$name = mysql_real_escape_string($_POST['store']);
$query="INSERT INTO products(catid, name) VALUES ('".$catid"','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
Please also look into PDO for the best way to handle DB queries like this.
try change this
"INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
to
"INSERT INTO products(catid, name)VALUES ('".$cat."','".$name."')";

Categories