php & mysql: Echo'ed table values cannot be re-inserted? - php

I have a table list of ingredients, which has about 5-6 values like cost, store, packaging, quanity, ect.
I then echo the data from the tables onto a drop down menu so they are selectable. However when I go to update or re-insert them into a new table, I get a error messaging saying "cost is not defaulted", even though it is.
So basically what is happening, is my drop down menu is NOT the database value itself when its time to use it to update it into a new table. Its stringified and its value is completely new. Is there a way to stop this from happening and tell mysql or PHP that I want the database values I originally put in when selected and not a stringified version of it?
<select name="ingredients_list" placeholder="Ingredients">
<option disabled selected value> -- select an ingredient -- </option>
<?php
$sql = "SELECT item, store
FROM ingredients
ORDER BY item";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($col = $result->fetch_assoc()) {
echo "<option>" . $col['item'] . " (" . $col['store'] . ") " . "</option>";
}
}
?>
Error Message:
Error: INSERT INTO meal_ingredients (meal_name, item) VALUES ('turkey', 'Bacon (Lidl)')
Field 'package' doesn't have a default value
It DOES have a value, but its not using it because its using the stringified "bacon" of the drop down, rather than the data on the database itself.

You are trying to insert only a part of the values for the table columns .. one of this column named package have a not null constrains so the partial insert
INSERT INTO meal_ingredients (meal_name, item) VALUES ('turkey', 'Bacon (Lidl)')
don't respect this constrain
could be you need
INSERT INTO meal_ingredients (meal_name, item,package )
VALUES ('turkey', 'Bacon (Lidl)', 'my_package_value')

Related

how to work with array updates

I am looking for some inspiration from someone wiser than me with PHP/MySQL.
In have a database application, and in this instance there are two primary tables and one child table.
Primary Table 1 - Documents
Primary Table 2 - JobDesriptions
Child Table - LnkDocuments_JobDescriptions, which as the title suggests is a one to many relational table between the Document and Job Description Table. In my Documents Table I have a field which is a lookup of JobDescriptions and presents options as a checkbox, this field is called 'AppliesTo', because of the way the application works, the field stores the results as a string, eg "1,2,3,4,5) I have used the explode function to turn this into an array and then insert each record into the child table, as I prefer 1-2-many relationships. This is the code that I have, and it works.
$jdarray = explode(',',$values['AppliesTo']);
foreach($jdarray as $item)
{
$sql2 = "INSERT INTO LnkDocuments_JobDescriptions (DocumentFk, JobDescriptionFk)
values ('".$keys["DocumentPk"]."', '$item')"; CustomQuery($sql2);
}
The problem I now have is that if that table gets updated, I need to also update the child table, i have tried this code (but quickly realised that it is wrong):
$jdarray = explode(',',$values['AppliesTo']);
foreach($jdarray as $item)
{
$sql = "SELECT * FROM LnkDocuments_JobDescriptions WHERE DocumentFk='".$keys["DocumentPk"]."' AND JobDescriptionFk='$item'"; ;
$num_rows = mysql_num_rows(CustomQuery($sql));
if ($num_rows > 0) //Delete Record
{
$sql2 = "DELETE FROM LnkDocuments_JobDescriptions WHERE DocumentFk='".$keys["DocumentPk"]."' AND JobDescriptionFk='$item'"; CustomQuery($sql2);
echo "JD FK : ".$item." deleted";
}
else //Insert Record
{
$sql3 = "INSERT INTO LnkDocuments_JobDescriptions (DocumentFk, JobDescriptionFk)
values ('".$keys["DocumentPk"]."', '$item')"; CustomQuery($sql3);
echo "JD FK : ".$item." added";
}
}
It occured to me that I need to compare differences in the arrays, but havent got a clue how to do this, but this is what I need:
If I can get $oldarray and $new array to compare, for example
if in old array there were values 1,2,3,4 and in $newarray there were values 1,2,3,5, I want the code to loop through each value to determine if there is a change, e.g. if value exists in old and new array then do nothing, if value exists in old array but not new then delete, if value exists in new array but not old then insert.
I have also thought about just deleting all associated records and adding again, but think this is bad practice and will result in high number primary key, also it is worth noting that in my example there are only 5 options, this is just for testing, in reality there could be dozens.
Thanks in advance
If you are trying to optimize things I'm not sure that reading the values already present in the table and then deleting only those are not in the new version while inserting the missing records is the best way to go. In my opinion it would be much faster to just delete everything in one query, then insert all records in one query. Try something like this:
$item_list = implode( ',' , $jdarray );
$delete_query = "DELETE FROM LnkDocuments_JobDescriptions WHERE DocumentFk='".$keys["DocumentPk"]."' AND JobDescriptionFk IN ( $item_list )";
CustomQuery($delete_query);
$document_key = "'" . $keys["DocumentPk"] . "'";
$item_list_to_insert = "($document_key, " . implode( "), ($document_key, ", $jdarray ) . ")";
$insert_query = "INSERT INTO LnkDocuments_JobDescriptions (DocumentFk, JobDescriptionFk) VALUES " . $item_list_to_insert;
CustomQuery($insert_query);
Note: I didn't test this, there might some debugging needed.

How to insert multiple values in a specific field in a table using mysqli? [duplicate]

This question already has answers here:
Is storing a delimited list in a database column really that bad?
(10 answers)
Closed 7 years ago.
I am working on a project and I I have a scenario like this:
I have many field in my table :
table_name : transaction_tbl
-id
-name
-description
-ref_number : text(datatype)
In my inserting here is my code:
$sql = "INSERT INTO transaction_tbl (`name`,`description`,`ref_number`) VALUES ('$name','$desccription',$ref_number)";
if ($conn->query($sql) === false){
trigger_error('Wrong SQL: ' . $sql . 'Error: ' . $conn->error , E_USER_ERROR);
}else {
echo "Successful ! Data is inserted in database ^__^" ;
}
As the name itself ref_number or reference number, so there will be a time that I will have a lot of reference number,how can I let it insert if it will have multiple values?
Thanks :)
UPDATE :
I want something like this :
name description ref_number
bag to be use 10359435846
05438547656
035848576
Its not a good practice to have multiple values in one cell (and you should never unless there is a serious reason). It violates basic db rules. Just split this to two tables and assign foreign keys to link them up.
Learn db normalization. There are lot of examples. In here you need to take your un-normalized (0NF) table to at least to 1st normalized level (1NF). But its advised to make it normalized at least up to 3rd level
google for db normalization tutorials. As you request below image will give you an idea(field names are not same as in your question).
First insert the values to table1(Member table) and get the insert id in php use $iid = mysqli_insert_id()
Next add the multiple values as seperate rows into the second table(database table) along with the primary key obtained in first step.
Keep in mind this is not a tutorial site. find more info on net.
for what purpose ? why don't you just insert a new row with the same name and description with different ref_number ?
but if you would like that , you can concatenate your new ref_number with the existing ..
first check if it already exist
get its value then concatenate the new ref number ..
or if it doesn't exist , insert a new row ..
$sql = "SELECT `ref_number` FROM `transaction_tbl`
WHERE `name`='$name' AND `description`='$description'";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
$new_ref = $row['ref_number'] . '|' . $ref_number;
$upd = "UPDATE `transaction_tbl` SET `ref_number`='$new_ref'
WHERE `name`='$name' AND `description`='$description'";
}
else
{
$ins = "INSERT INTO transaction_tbl (`name`,`description`,`ref_number`)
VALUES ('$name','$desccription',$ref_number)";
mysql_query($ins);
}

SQL query adding a duplicate rows on every run in php

Below piece of code on every execution is creating two rows. Just for testing purpose I commented out php variables and replace them with hardcoded value like '1', '3' etc in VALUE clause of INSERT query. I could not find out the exact cause, so putting here the entire code. Here TaskID is Auto incremented column.
/* CONNECT TO DATABASE TO ADD THIS TASK IN PT_TASK TABLE */
if ($ConnectStatus) {
echo '1';
$Query = "INSERT INTO PT_TASKS (TaskID, ParentID, Title, AssignedTo, Category, Status, Zone, Created, CreatedTime, LastModified, ProgressPercent, Notes, StartDate, TargetDate, ActualStart, ActualEnd)
VALUES (' ','12449','3','1','1','1','1','1','1','1','1','1','1','1','1','1')";
// VALUES (' ','$ParentID','$Title','$AssignedTo','$Categories','$Status','$Zone','$Created','$CreatedTime','$LastModified','$ProgressPercent','$Notes','$PlannedStart','$PlannedEnd','$ActualStart','$ActualEnd')";
if (!mysql_query($Query,$con))
{
die('Error: ' . mysql_error());
}
else
{
echo "updated1";
}
$Query_result = mysql_query($Query);
}
else {
?><div class="Error">Database Connection Failed. Can not create this project. </div><?php
}
Whenever I refresh this page two rows get added in table PT_TASKS. Ideally only one row should get added in PT_TASKS. Not sure what mistake I am making. Please help.
Take out the last
$Query_result = mysql_query($Query);
Since you are already executing the query before that as
if (!mysql_query($Query,$con))

Adding multiple rows to table with auto_increment column

Im trying to insert Data into a table named team. The table holds 4 colums. selection_id(primary key), player_name, position, and fixture id.
The selection_id has a value of auto_increment. Im adding the player names and position to the table. However the problem is, for each value it extracts out of the arrays, $playnames and $positions, the selection_id updates. Like this:
This is not what I want. 5 names should be stored (thus storing the team selected) in the table before the selection_id updates. OR for each new row, where a new team selection is made, the selection_id must be the same.
Im not sure how to get around this problem. I thought about doing another query after the data has been inserted to overwrite the selection_id and making all the rows (in this case) equal to 117. But im sure this is not the most effecient way to do it.
If anyone can give me a couple of pointers it would be greatly appreciated.
Code follows:
if ( isset($_POST['submit']) ) {
$player_ids = array_map('intval', $_REQUEST['players']);
var_dump($player_ids);
$query = 'SELECT `name`, `position`
FROM `player_info`
WHERE `player_id` IN (' . implode(',', $player_ids) . ')';
$return_names = mysql_query($query) or die(mysql_error());
while ( $row = mysql_fetch_assoc($return_names) ) {
$selected[] = $row['name'];
$position[] = $row['position'];
}
for ($i=0; sizeof($selected) > $i; $i++){
$sql = mysql_query("INSERT INTO `team`(`selection_id`,`player_position`,`player_name`) VALUES ('selection_id\"\"','$position[$i]','$selected[$i]')")
or die(mysql_error());
echo $selected[$i];
echo $position[$i];
echo'<br>';
}
var_dump($selected);
}

How to avoid duplication of mysql table entries?

I seem to be getting duplicating table entries with using this PHP code. Every time I hit refresh, when it inserts what I have hard coded and prints previous entries (even if they values are the same).
What I want to know is how can I avoid duplication if the values are the same? I also do not want the code to duplicate entries when the page refreshes.
//insert data entries
mysqli_query ($con, "INSERT IGNORE INTO alarms(Title, Description, DT)
VALUES('get', 'Agha will eat', '2013-08-05 00:15:12')");
This is the print function.
//print out data entries
$result = mysqli_query($con,"SELECT * FROM alarms");
while ($row = mysqli_fetch_array($result))
{
echo $row['alarmID'] . " <br> " . $row['Title'] . " <br> " . $row['Description'] . " <br> " . $row['DT'];
}
Create a UNIQUE constraint in your alarm table based on the values which you want to be unique.
Suppose that for every row, you want the Title, Description and DT triples to be unique. Then, add the UNIQUE constraint in your alarm table in the following way -
ALTER TABLE alarm ADD CONSTRAINT uc_alarm UNIQUE (Title, Description, DT)
If you do this, then whenever you try to insert a row whose Title, Description and DT matches with those of an existing rows, MySQL will generate an error and reject that insert command.
Check out this short tutorial for a overview of the UNIQUE constraint.

Categories