I want to select several rows from my database and get each id where the name, material and size fits the binded value. I have tried doing this, but I only get the first row back:
foreach($_POST["txtName"] as $key => $name){
if(!empty($name) || !empty($_POST["txtMaterial"][$key]) || !empty($_POST["txtSize"][$key])){
echo $name.' '.$_POST["txtMaterial"][$key].' '.$_POST["txtSize"][$key];
$sQuery = $db->prepare('SELECT * FROM products WHERE name = :sName AND material = :sMaterial AND size = :sSize');
$sQuery->bindValue(':sName', $name);
$sQuery->bindValue(':sMaterial', $_POST["txtMaterial"][$key]);
$sQuery->bindValue(':sSize', $_POST["txtSize"][$key]);
$sQuery->execute();
$aOrders = $sQuery->fetchAll();
foreach($aOrders as $aOrder){
echo 'x';
}
}
}
From the echo before the query I get this back:
" 3 20BACURI 2 4ELVA "
Which is the material, size, name and material, size, name of two products. However, I only get the row of the first one back. Can anyone help me out why that is?
<input name='txtName[]' class='txtName' type='text'><div class='nameOfProduct'>".$aCategoryName['name']."</div>
<div class='add'>
<div id='adding'>+</div>
</div>
The value of the name is added in js when clicked on the .add class:
$('.add').click(function(){
$placeholder = $(this).siblings('.nameOfProduct').html()
$(this).siblings('.txtName').val($placeholder)
})
Related
I am busy making a multi-shop shopping site like amazon.com, ebay, carousell.com etc...
Now when users create a listing I made a custom fields system that get the custom fields from a mysql table then outputs them into the form.
The Code:
Okay so first this is the listings table:
ID
list_title
list_brand
seller_id
1
Two sticks
Mr Sticks
1012
Then we have listings_meta which is where I store the custom fields like for a pillow it would be type of filling or for a stick it would be color of stick:
ID
listing_id
meta_key
meta_value
1
1
stick_color
brown
Now the meta key comes from a database table called [form_fields] which is linked the the categories like this
[form_fields]:
ID
meta_key
type
meta_link
1
stick_color
select
0
2
stick_length
input
0
3
rock_weight
input
0
4
brown
option
1
5
blue
option
1
And the category table[cats]:
ID
category
4
Sticks
5
Stones
Link custom fields and categories[cat_meta]:
ID
meta_id
cat_id
1
1
4
2
2
4
3
3
5
So now that you know how the items link with each other lets dive into the PHP code:
Now fist when a user clicks create product that will be given a popup asking which category they want to list the product thats done with a simple select query then they will be redirected to a new page called new_product.php?cat=[id of category from database ID]
new_product.php?cat=4
Now some of the fields are the same for all products they are the ones in listings table
But for custom fields its a bit more complex
:
<input type="text" name="list_title " placeholder="Title">
</br>
<input type="text" name="list_brand " placeholder="Brand">
</br>
<?php //get custom fields from custom_inputs table
//query the database for fields id and
$stmt = $conn->prepare("SELECT `meta_id ` FROM `cat_meta` WHERE `cat_id` = ?");
$stmt->bind_param("i", $_GET['cat']);
$stmt->execute();
$stmt_results = $stmt->get_result(); // get result
while($row_get = $stmt_results->fetch_assoc()){
$field_id[] = $row_get['meta_id ']; //store all id's in array
}
if(empty($field_id)){ //no custom field found in database
return 0;
}else{
foreach($field_id as $field_id){ //loop ID's to get multiple
$stmt = $conn->prepare("SELECT `meta_key `, `type ` FROM `form_fields` WHERE `ID` = ?");
$stmt->bind_param("i", $field_id);
$stmt->execute();
$stmt_results = $stmt->get_result(); // get result
while($row = $stmt_results->fetch_assoc()){
$field_name[] = $row['meta_key']; //get key aka title
$field_type[] = $row['type']; //get the type of input
}
}
}
foreach ($field_name as $index => $field) { //combine the type and meta key
$type = $field_type[$index];
if($type === "select"){ //field type is a select
echo '</br><select name="body['.$field.']">';
echo '<option selected Disabled value="">Select Option</option>';
//get options from `form_fields` linked to this meta_id
$stmt = $conn->prepare("SELECT `meta_key` FROM `form_fields` WHERE `meta_linked` = ? AND `field_type` = 'option'");
$stmt->bind_param("s", $field);
$stmt->execute();
$stmt_results = $stmt->get_result(); // get result
while($row = $stmt_results->fetch_assoc()){
echo '<option value='.$row['meta_key '].'>'.$row['meta_key'].'</option>';
}
echo '</select>';
}
if($type === "input"){ //field type is a user input
echo "<input name='body[$field]' placeholder='$field'>";
}
}
?>
Yes I know the code is very messy but I will clean it up before it is pushed but my issue is I feel like this seems over-complex/not efficient, Can anyone recommend a better way to build custom fields based on the category that was selected.
Also i do not include a lot of html and other php processing code as i dont think it needs to be included but if you need more info i will give it :)
I have a script that is pretty straight forward in theory, where I"m trying to select relational data on a development DB2 database, and insert into a separate production db2 server (creating new IDs and relationships on the production side in the process).
So in this script, I:
Select from the dev ITEM table
Store the original primary key
insert the data into the dev ITEM table
Get the ID of the newly inserted one
select SUBITEM from dev with the original ID
for each subitem I insert the data into the prod SUBITEM table with the newly created ITEM ID as the relationship
The problem is the script actually runs successfully, but as it goes, it simply increases by one so even though it inserts each ITEM correctly, it ends up just getting EVERY subitem in the database and storing the original (1st row's) ID. FOr instance:
My first ITEM select returns ID 1204. By the time I let it run for several items, my ITEM table shows records with IDs: 1204,1205,1206 and 1207
That's correct, but when I look at the subITEMS table, I have 10 subITEM records all with itemID of 1204. So it got the right subitem for each iteration of ITEMS but only ever inserted the very first newID variable.
What did I do wrong here:
if($DB2connDEV && $DB2connPROD){
$getDevItems = "
SELECT
itemt_ID,
DESCRIPTION
FROM itemt
";
$stmt = odbc_exec($DB2connDEV, $getDevItems);
while($gettingDevItems = odbc_fetch_array($stmt)){
$rows[] = $gettingDevItems;
}
foreach($rows as $row){
$prepInsert = odbc_prepare($DB2connPROD, "INSERT INTO itemt (itemt_id, description) VALUES(?,?)");
$originalID = $row['itemt_ID'];
$description = $row['DESCRIPTION'];
$insertTable = odbc_execute($prepInsert, array($description));
//Get newly created ID
$getIdentity = "SELECT IDENTITY_VAL_LOCAL() AS LASTID FROM SYSIBM.SYSDUMMY1";
$stmt = odbc_exec($DB2connPROD, $getIdentity);
$row = odbc_fetch_array($stmt);
$newID = $row['LASTID'];
if($newID) {
echo "Last Insert ID is : " . $newID . "\n";
} else {
echo "No Last insert ID.\n";
}
//Get subItems and insert
$getSubItems = "SELECT NAME, DESCRIPTION
FROM SUBITEMT
WHERE itemt_ID = $originalID";
$selectSubItems = odbc_exec($DB2connDEV, $getSubItems);
while($gettingSubItems = odbc_fetch_array($selectSubItems)){
$subItemRows[] = $gettingSubItems;
}
foreach($subItemRows as $subItemRow){
$subItemPrepInsert = odbc_prepare($DB2connPROD, "INSERT INTO subitemt (itemt_id, NAME, DESCRIPTION) VALUES(?,?,?)");
$subItemName = $subItemRow['NAME'];
$subItemDescription = $subItemRow['DESCRIPTION'];
$subtaskInsertExec = odbc_execute($subtaskPrepInsert, array($newID, $subItemName, $subItemDescription));
//get newly created ID for subitem
$getsubtaskID = "SELECT IDENTITY_VAL_LOCAL() AS LASTID FROM SYSIBM.SYSDUMMY1";
$subtaskIDSTMT = odbc_exec($DB2connPROD, $getsubtaskID);
$newsubItemRow = odbc_fetch_array($subtaskIDSTMT);
$newSubItemID = $newsubItemRow['LASTID'];
if($newSubItemID) {
echo "Last Insert subItem ID is : " . $newSubItemID . "\n";
} else {
echo "No Last insert subItem ID.\n";
}
}
}
odbc_close($DB2connPROD);
odbc_close($DB2connDEV);
}
The problem is that you're not clearing out $subItemRows between iterations of the main loop. So each time you're adding the new subitems to the subitems from the previous iterations.
Put
$subItemRows = array();
before the loop:
while($gettingSubItems = odbc_fetch_array($selectSubItems)){
$subItemRows[] = $gettingSubItems;
}
Hi I'm trying to display all car names,their images ,rental rate all from different tables in a page. How do I get id for each car in select statement?
for instance:
while($row_showall = mysql_fetch_array($result_showall))
{
$car_id[] = $row_showall['carName_id'];
}
foreach($car_id as $id)
{
$id;
echo $id.'<br/>';
//result is
27773
27774
27778
27779
}
when I place $id outside foreach loop obviously it doesn't loop and the result is
2779.
so when I use select statement here like this:
$query_showdays_1="SELECT ........WHERE car_name.carName_id='$id'";
how do I make it select each and every of the car id instead of only one id?
I'm guessing that your table name is cars, because you haven't provided that info. If it's not then change the cars with your table name.
$query_showdays_1 = "SELECT * FROM cars";
while ($row_showall = mysql_fetch_array($query_showdays_1))
{
echo $row_showall['carName_id'] . '<br />';
}
I am trying to work out the best way of doing this but not sure how. Could somebody help me please?
Say i have 4 marks - Gold, silver, Bronze and In Development
One of these marks will be a value for $gsb['gsb'] from the db.
The code below gets the courses and echos back the img and link.
The bit i am struggling with is how to rank the 4 values above, so that if there are more than one result returned it will get the highest or lowest value depending on the chosen ranking and only echo back that one result/img
Hope this is clear. I would be grealy appreciative of any help/guidance.
$metacourses = mysql_query("SELECT * FROM mdl_course_meta where parent_course = $courseid");
while($parentcourse = mysql_fetch_assoc($metacourses)){
//Select GSB for course
$parentcourseid = $parentcourse['child_course'];
$gsb = mysql_fetch_array(mysql_query("SELECT * FROM mdl_gsb_content where course = $parentcourseid"));
//Used for $img name
if ($gsb['gsb']=="") {$thegsbscore = "in_development";}
else {$thegsbscore = $gsb['gsb'];}
if ($viewgsb == 'Yes'){
$img = '<div align="center"><img src="'.$CFG->wwwroot.'/blocks/gsb/images/'.strtolower($thegsbscore).'.png" width="90" height="98"></div>';
$link = '<p align="center"><b>How can I improve my course medal?</b></p>';
}
else {
$img = '';
$message = '';
$viewgsb = '';
$link = '';
}
}
$this->content = new stdClass;
$this->content->text = $message . $img . $link;
$this->content->footer = '';
return $this->content;
return $this->content->text;
Assign weightage to your values, preferably in a table.
Use like this:
TABLE_WEIGHT (It's a better idea to store these in a separate table, that way you can always add/delete more scores, irrespective of other tables)
ID(PRIMARY KEY) SCORE_NAME(VARCHAR) SCORE_WEIGHTAGE(INT/ENUM)
1 In Development 1
2 Bronze 2
3 Silver 3
4 Gold 4
Now, you can always sort your data by using a SQL JOIN in your second query. Also, in case of multiple results, you can use PHP's usort to filter your results.
Hope this helps.
you can do this multiple ways, order by a filed that maps weight, join to another tables that has weight and get the weights. pushpesh is the best solution you would then do
SELECT * FROM mdl_gsb_content
where course = $parentcourseid
join table_weight
on table_weight.score_name = mdl_gsb_content.gsb
order by table_weight.SCORE_WEIGHTAGE.
(assuming gsb is he score)
not tested but should do the trick.
Edit By Codded after testing:
SELECT * FROM mdl_gsb_content
JOIN mdl_gsb_scores on mdl_gsb_scores.score = mdl_gsb_content.gsb
WHERE mdl_gsb_content.courseid = $parentcourseid
ORDER by mdl_gsb_scores.rank ASC
LIMIT 1
After implementing Pushpeshs weightage table and a work around from encodes SQL query i finally came up with the correct way.
$metacourses = mysql_query("SELECT * FROM mdl_course_meta where parent_course = $courseid");
//Select GSB for course
$types = array();
while(($row = mysql_fetch_assoc($metacourses))) {
$types[] = $row['child_course'];
}
$theids = implode(',',$types);
$gsb = mysql_query("
SELECT * FROM mdl_gsb_content
JOIN mdl_gsb_scores on mdl_gsb_scores.score = mdl_gsb_content.gsb
WHERE mdl_gsb_content.courseid IN ($theids)
ORDER by mdl_gsb_scores.rank ASC
LIMIT 1");
while($score = mysql_fetch_assoc($gsb))
//Work out img
$thegsbscore = $score['gsb'];
if ($viewgsb == 'Yes'){
$img = '<div align="center"><img src="'.$CFG->wwwroot.'/blocks/gsb/images/'.strtolower($thegsbscore).'.png" width="90" height="98"></div>';
$link = '<p align="center"><b>How can I improve my course medal?</b></p>';
$message = '<div align="center">Your Unit VLE is:'.print_r($types).'</div><br />';
}
else {
$img = '';
$message = '';
$viewgsb = '';
$link = '';
}
I have been searching for an answer to this for about an hour and can't find what I am looking for...
I have 3 dependent select boxes on a INSERT form.(drop_1, drop_2, drop_3) Each of their values (int) represent the same field in the database called category.
I am looking for a way to choose only the highest value of the three as the value that gets inserted into the category field.
Here is what I have been trying (obviously doesn't work):
$drop_1 = ($_POST['drop_1']);
$drop_2 = ($_POST['drop_2']);
$drop_3 = ($_POST['drop_3']);
$category = max($drop_1, $drop_2, $drop_3);
This works only if I select an option from each of the 3 boxes, but if I select an option from only 1 or 2 of the boxes the form gets submitted to the DB with blank values.
your php seems fine:
<?php
$_POST['drop_1'] = 100;
$_POST['drop_2'] = null;
$drop_1 = ($_POST['drop_1']);
$drop_2 = ($_POST['drop_2']);
$drop_3 = ($_POST['drop_3']);
$category = max($drop_1, $drop_2, $drop_3);
echo $category;
would output:
100
so, problem is with the form.
$drop_1 = mysql_real_escape_string($_POST['drop_1']);
$drop_2 = mysql_real_escape_string($_POST['drop_2']);
$drop_3 = mysql_real_escape_string($_POST['drop_3']);
$query = "INSERT INTO table1 (category)
SELECT GREATEST('$drop_1', '$drop_2', '$drop_3') as new_cat ";