I searched, but I couldn't find an answer anywhere here. I have a multiselect box that will take each selection and explode it into individual data entries into a MySQL DB. Here is the code
$arr = explode(",",$values["account_id"]);
$j = count($arr);
for($i = 0; $i < $j ; $i++)
{
$strInsert = "update accounts_data set balance=balance+".$values["debit"]." where id='".$arr[$i]."'";
DB::Query($strInsert);
}
The field account_id is an integer field, but if I have more than 2 items selected, the code breaks. If account_id is set to a VARCHAR, I can select everything and it works just as I need it to updating every account balance with the new debit. I'm not quite sure why it works for a VARCHAR and not an INT, and I can't quite figure out how to make it work after a month of trial and error. I was wondering if anyone had an idea that is smarter than I am.
not sure I understood about your explanation about varchar and int.
Here is a way I would do it:
$values["account_id"] = "30,56,78";
$values["debit"] = 100;
foreach(explode(",", $values["account_id"]) as $account)
{
$strInsert = "update accounts_data set balance=balance+" . $values["debit"] ." where id=" . $account;
echo $strInsert . PHP_EOL;
// DB::Query($strInsert);
}
Hope this helps something.
Related
I'm developping a quiz app, and for this I use 2 different tables:
One is "question", where there are questions and answers
the other one is "answer_quizz_user" with a unique id depending on the candidate, where I have exactly the same column than "question", with the answer in a random order.
My goal is to show the same question with the same answer in a random order, and to save it in the db like this.
This is what my table looks like
I would like to select the column by pair
(answer"X"_right_answer is a boolen which mean right or wrong answer):
(answer1,answer1_right_answer),
(answer2,answer2_right_answer),
(answer3,answer3_right_answer),
(answer4,answer4_right_answer),
(answer5,answer5_right_answer),
(answer6,answer6_right_answer)
to shuffle it, and insert it in "answer_quizz_user".
I tried different things like :
for ($n=1; $n <=6 ; $n++) {
INSERT INTO answer_quizz_user SELECT
answer".$n." FROM question
WHERE question_question = "q1"
ORDER BY RAND()}
but none worked. I have absolutely no idea how to manage this select->insert. I know that I should have done another table for answers, but now it's too late, the app is almost finish, I just need this random part...
Thanks for your help and sorry for my bad english..
Something like this should work, although your database structure is quite bad. Next time use a separate table for your answers.
It isn't a copy-and-paste solution (I would needed to know more about your code to do that), but I hope it will be enough to set you on the right path.
The basic idea is, you get your pairs from the db, put them in an array, use php's built-in shuffle() function, then insert your rows.
// Gets the required row from database
$query = "select * from question where question_question = 'q1';";
$result = $db->query($query);
if($result->num_rows > 0) {
$question = $result->fetch_assoc();
// Create an array with the pairs
$pairs = array();
for($n = 1; $n <= 6; $n++) {
$pairs[] = array(
'Answer' => $question['answer' . $n],
'IsRight' => $question['answer' . $n . '_right_answer'],
);
}
// Arrange pairs in random order
shuffle($pairs);
// Insert the new rows
foreach($pairs as $pair) {
$query = "insert into answer_quizz_user values ('" . $pair['Answer'] . "', '" . $pair['IsRight'] . "');";
$db->query($query);
}
}
I hope, I could be of any help.
I have a page with 100 checkboxes.. on and off. These checkboxes are named "box1" "box2" "box3" etc. They are pulled from a single row/col in a table where I exploded 1|0|1|0|1 into individual checkbox inputs.
My issue is that when I try to update them, I can't figure out how I can get them back into a single string to put them back into the same column. Here is what I have.. but clearly it doesn't work. Some of this stuff is new to me. Any advice would help.
$i = 1;
while($i < 101){
$thisBox = $_POST['box'][$i];
if($thisBox != 1){$thisBox = 0;}
$boxData .= $thisBox . "|";
$i++;
}
It just shows up with 100x "|" and I am unsure if it's possible to create the $_POST['box##'] with each loop.
try $thisBox = $_POST['box'.$i]
try this,
$thisBox = $_POST["box$i"] == "on" ? 1 : 0;
$boxData .= $thisBox . "|";
No need of if condition
I am pretty new to PHP, but have tried searching for other questions similar to mine and been unable to find anything that is close enough to my situation to help me solve this.
I am trying to code a web page that allows users to select as many or as few items as they would like to order. The item values are identical to their Primary Key in the Item table.
Once submitted, each different item value should be input into the same row of a database table based on the date{pk}. Within that row, there are numerous columns: Item1ID, Item2ID, Item3ID, etc.
So far, the value of each item selected is assigned to a new array. However, I cannot simply input the array values into a column -- I need each array index to be placed into a sequential column. The code is below:
$date = new DateTime();
$td = $date->format('Y-m-d');
$x = 1;
$checkedItems = $_POST['Item'];
$count = count($checkedItems);
echo $count;
$foodID = "Item".$x."ID";
While($x<=$count){
if(isset($_POST['Item'])){
if (is_array($_POST['Item'])) {
foreach($_POST['Item'] as $values){
$selectedFoods = substr($values,0,4);
$addFoodOrderQuery= sprintf("UPDATE WeeklyBasketFoodOrder SET '%s' = %s WHERE `foodOrderDate` = '%s'",
$foodID, $selectedFoods, $td);
$result= mysqli_query($db, $addFoodOrderQuery);
}
}
} else {
$values = $_POST['Item'];
echo "You have not selected any items to order.";
}
$x++;
}
If you need any further clarification, please let me know. After submitting the code, the database item#ID tables are different, but they are now empty instead of "NULL."
I am trying to update an MS Access table using an array here is my code
for($i = 1; $i<=$rows; $i++)
{
$seedsize[$i] = $_POST['packageType'.$i];
$RefNo[$i] = $_POST['field'.$i];
(int)$qtyOrder[$i] = $_POST['ordered'.$i];
(int)$qtyDel[$i] = $_POST['delivered'.$i];
$unitPrice[$i] = $_POST['unitPriceDtl'.$i];
$ref2[$i] = $_POST['grade'.$i];
//$date[$i] = $_POST['myDate'.$i];
}
$InvoiceID = $_SESSION['InvoiceID'];
$sql = "UPDATE
[Tbl_Invoice_Details]
SET
[Seed Size]=?,
[RefNo]=?,
[Quantity Ordered]=?,
[Quantity Delivered]=?, [Ref2]=?,
[PricePerUnit]=?
WHERE
[Invoice_ID]=?";
$data = $conn2->prepare($sql);
for($x = 1; $x <= 4; $x++)
{
$data->execute(array($seedsize[$x], $RefNo[$x], $qtyOrder[$x], $qtyDel[$x], $unitPrice[$x], $ref2[$x], $InvoiceID));
echo $RefNo[$x]."<br/>";
}
I am getting this error "Invalid character value for cast specification: -3030 [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression."
Thank you for your help!
Have you confirmed that there isn't any null values in the data? Null values might be causing the cast error.
I would suggest to cast all numeric values:
for($i = 1; $i<=$rows; $i++)
{
$seedsize[$i] = $_POST['packageType' . $i]; // Not sure about this one
$RefNo[$i] = (int)$_POST['field' . $i];
$qtyOrder[$i] = (int)$_POST['ordered' . $i];
$qtyDel[$i] = (int)$_POST['delivered' . $i];
$unitPrice[$i] = (float)$_POST['unitPriceDtl' . $i];
$ref2[$i] = $_POST['grade' . $i]; // Not sure about this one
//$date[$i] = $_POST['myDate' .$i];
}
Please note that the cast should be on the right side of the assignment operator.
Why is 4 hard coded in the 2nd for loop? Just curious.
What I think is the issue is(int)$qtyOrder[$i] or (int)$qtyDel[$i] or really anything else. The error is saying the data it expected to get is not what it got, so somewhere you sent ABC when it wanted only 123 (Numbers) for example. You should do any processing on the POST'ed information, maybe somting like:
$qtyOrder[$i] = intval($_POST['ordered'.$i]);
$qtyDel[$i] = intval($_POST['delivered'.$i]);
I've never done what your doing percisly but I think this will send you on the right track. Here is the PHP manual page I looked at.
I previously designed the website I'm working on so that I'd just query the database for the information I needed per-page, but after implementing a feature that required every cell from every table on every page (oh boy), I realized for optimization purposes I should combine it into a single large database query and throw each table into an array, thus cutting down on SQL calls.
The problem comes in where I want this array to include skipped IDs (primary key) in the database. I'll try and avoid having missing rows/IDs of course, but I won't be managing this data and I want the system to be smart enough to account for any problems like this.
My method starts off simple enough:
//Run query
$localityResult = mysql_query("SELECT id,name FROM localities");
$localityMax = mysql_fetch_array(mysql_query("SELECT max(id) FROM localities"));
$localityMax = $localityMax[0];
//Assign table to array
for ($i=1;$i<$localityMax+1;$i++)
{
$row = mysql_fetch_assoc($localityResult);
$localityData["id"][$i] = $row["id"];
$localityData["name"][$i] = $row["name"];
}
//Output
for ($i=1;$i<$localityMax+1;$i++)
{
echo $i.". ";
echo $localityData["id"][$i]." - ";
echo $localityData["name"][$i];
echo "<br />\n";
}
Two notes:
Yes, I should probably move that $localityMax check to a PHP loop.
I'm intentionally skipping the first array key.
The problem here is that any missed key in the database isn't accounted for, so it ends up outputting like this (sample table):
1 - Tok
2 - Juneau
3 - Anchorage
4 - Nashville
7 - Chattanooga
8 - Memphis
-
-
I want to write "Error" or NULL or something when the row isn't found, then continue on without interrupting things. I've found I can check if $i is less than $row[$i] to see if the row was skipped, but I'm not sure how to correct it at that point.
I can provide more information or a sample database dump if needed. I've just been stuck on this problem for hours and hours, nothing I've tried is working. I would really appreciate your assistance, and general feedback if I'm making any terrible mistakes. Thank you!
Edit: I've solved it! First, iterate through the array to set a NULL value or "Error" message. Then, in the assignations, set $i to $row["id"] right after the mysql_fetch_assoc() call. The full code looks like this:
//Run query
$localityResult = mysql_query("SELECT id,name FROM localities");
$localityMax = mysql_fetch_array(mysql_query("SELECT max(id) FROM localities"));
$localityMax = $localityMax[0];
//Reset
for ($i=1;$i<$localityMax+1;$i++)
{
$localityData["id"][$i] = NULL;
$localityData["name"][$i] = "Error";
}
//Assign table to array
for ($i=1;$i<$localityMax+1;$i++)
{
$row = mysql_fetch_assoc($localityResult);
$i = $row["id"];
$localityData["id"][$i] = $row["id"];
$localityData["name"][$i] = $row["name"];
}
//Output
for ($i=1;$i<$localityMax+1;$i++)
{
echo $i.". ";
echo $localityData["id"][$i]." - ";
echo $localityData["name"][$i];
echo "<br />\n";
}
Thanks for the help all!
Primary keys must be unique in MySQL, so you would get a maximum of one possible blank ID since MySQL would not allow duplicate data to be inserted.
If you were working with a column that is not a primary or unique key, your query would need to be the only thing that would change:
SELECT id, name FROM localities WHERE id != "";
or
SELECT id, name FROM localities WHERE NOT ISNULL(id);
EDIT: Created a new answer based on clarification from OP.
If you have a numeric sequence that you want to keep unbroken, and there may be missing rows from the database table, you can use the following (simple) code to give you what you need. Using the same method, your $i = ... could actually be set to the first ID in the sequence from the DB if you don't want to start at ID: 1.
$result = mysql_query('SELECT id, name FROM localities ORDER BY id');
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[(int) $row['id']] = array(
'id' => $row['id'],
'name' => $row['name'],
);
}
// This saves a query to the database and a second for loop.
end($data); // move the internal pointer to the end of the array
$max = key($data); // fetch the key of the item the internal pointer is set to
for ($i = 1; $i < $max + 1; $i++) {
if (!isset($data[$i])) {
$data[$i] = array(
'id' => NULL,
'name' => 'Erorr: Missing',
);
}
echo "$i. {$data[$id]['id']} - {$data[$id]['name']}<br />\n";
}
After you've gotten your $localityResult, you could put all of the id's in an array, then before you echo $localityDataStuff, check to see
if(in_array($i, $your_locality_id_array)) {
// do your echoing
} else {
// echo your not found message
}
To make $your_locality_id_array:
$locality_id_array = array();
foreach($localityResult as $locality) {
$locality_id_array[] = $locality['id'];
}