foreach Insert arrays as columns - php

I have four arrays:
$qtys = $_POST['qty'];
$colours = $_POST['colour'];
$sizes = $_POST['size'];
$names = $_POST['name'];
I want these to go into a mysql table like so:
qty | colour | size | name
-------------------------------------------
$qtys[0] | $colour[0] | $size[0] | $name[0]
$qtys[1] | $colour[1] | $size[1] | $name[1]
I've tried various things, including this:
foreach($qtys as $value) {
$i = 0;
mysql_query("INSERT INTO table (qty,colour,size,name) VALUES ('$qtys[$i]','$colours[$i]','$sizes[$i]','$names[$i]')");
$i++;
}
...but to no avail. Can anyone suggest a different INSERT statement that will get the data in the table? Do I need to iterate in the loop? I'm sure $qtys as $value is incorrect but have tried so many things with no luck.

First of all, you are resetting the counter each iteration, put $i = 0 outside of the loop if you want to do it this way.
$i = 0;
foreach($qtys as $value) {
mysql_query("INSERT INTO table (qty,colour,size,name) VALUES ('$qtys[$i]','$colours[$i]','$sizes[$i]','$names[$i]')");
$i++;
}
A better (cleaner) way would be something like:
for ($i = 0; $i < $qtys.count(); $i++) {
mysql_query("INSERT INTO table (qty,colour,size,name) VALUES ('$qtys[$i]','$colours[$i]','$sizes[$i]','$names[$i]')");
}
Also, are you sure that the arrays are always the same length? Otherwise you risk getting a index out of bounds problem..

Simply use for loop will be ok, AND REMEMBER ESCAPE USER INPUT.
for($i =0, $count = count($qtys); $i < $count; $i++) {
mysql_query("INSERT INTO table (qty,colour,size,name) VALUES ('$qtys[$i]','$colours[$i]','$sizes[$i]','$names[$i]')");
}

$sql = "INSERT INTO table (qty,colour,size,name) VALUES ";
$inserts = array();
for($i=0 ; $i < count($qtys); $i++) {
$inserts[] = "('$qtys[$i]','$colours[$i]','$sizes[$i]','$names[$i]')";
}
$sql .= implode(',', $inserts);
mysql_query($sql);
No need to run query again and again.

Related

how to divide students in sql

I want to divide student group-wise and store them in database
students 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15.....20
Example: Total no.of students 20
Make 4 students per group (1,2,3,4 group1 and 5,6,7,8 group2 etc.....)
Then there should 5 groups created
i tried like this where the mistake i am doing in for loops.
$studentQuery = $conn->query("
select s.student_pid,i.email,s.student_email,s.student_fname,
s.student_lname,s.profile_pic from r_job_invitations i
LEFT JOIN
tbl_students s
ON
i.email = s.student_email
where i.id_job = ".$jobID." and inv_res = 1");
$totalIndividuals = mysqli_num_rows($studentQuery);
$groups = round($totalIndividuals/5,0,PHP_ROUND_HALF_DOWN);
for ($j = 1; $j <= $groups; $j++) {
for ($i = 0; $i <= $totalIndividuals; $i++) {
$GroupsQuery = $conn->query("INSERT INTO
r_test_group (student_id,job_id,group_name)
values ('".$studentResults['student_pid']."',
'".$jobID."','Group'".$j." )");
}
}
$stuData = array();
while($studentResults = $studentQuery->fetch_array()) {
$stuData[] = $studentResults;
}
$totalIndividuals = mysqli_num_rows($studentQuery);
$groups = round($totalIndividuals/$gd_individuals,0,PHP_ROUND_HALF_DOWN);
$count=0;
for($j = 0; $j<$groups; $j++) {
for($i =0; $i< $gd_individuals; $i++) {
if($stuData[$count]['student_pid']) {
echo "INSERT INTO r_test_group (student_id,job_id,group_name) values (".$stuData[$count]['student_pid'].", ".$jobID.",Group".$j." )";
$count++;
}
}
}
exit;
first forloop is to divide groups.
Second forloop is to divide for students.
You could use flooring to translate a student id to a group id:
INSERT INTO r_test_group
(student_id,job_id,group_name)
SELECT student_pid, id_job, CONCAT('group', FLOOR((student_id - 1) / 4) + 1))
FROM tbl_students s
JOIN r_job_invitations j ON j.email = s.student_email
Considering there is no gaps between the records
select Concat('group',(your_col - 1 ) / 4 + 1 )
From yourtable
Note : This will not work when there is gaps. If you have gaps then you need to generate row number for each row then replace then student_id with row number in my query.
I think your code giving you more student then you are looking for. in your code in first loop its running for number of groups time then for each group in next for loop its running for all students in each group.
$limit = (int)($totalIndividuals/$groups);
for($j =0; $j<$groups;)
{
for($i =0; $i<$totalIndividuals; $i++)
{
if($i % $limit == 0)
$j++;
$GroupsQuery = $conn->query("INSERT INTO r_test_group (student_id,job_id,group_name) values ('".$studentResults['student_pid']."', '".$jobID."','Group'".$j." )");
}
}

can't get the logic to restart looping

I have 15 databases 1,2,3,4, ... 15
and I have the variable $i default at 1 and each time the $i count gets to 3, $i restarts the looping from 1 again until 3 and it will stop until value from database is done counting.
$detailPsycho = mysql_query("SELECT * FROM `psycho` WHERE `flag` = 2 ") or die(mysql_error());
while($detail = mysql_fetch_array($detailPsycho)){
for($i = 1;$i<=3;$i++){
echo $detail['sequence']."&".$i." <br>";
}
}
and run over like this :/
1&1
1&2
1&3
2&1
2&2
2&3
You try to do a loop (for{}) in a loop (while{}) which is a complicated way of doing something trivial. This is the "while+for" result :
$detailPsycho = mysql_query("SELECT * FROM `psycho` WHERE `flag` = 2 ") or die(mysql_error());
i = (int) 1;
while($detail = mysql_fetch_array($detailPsycho)) {
echo $detail['sequence']."&".$i." <br>";
$i++;
if ($i > 3) $i = 1;
}

PHP loop stops unexpectly

I have a table (table3) in MYSQL with 99 text fields (field1, filed2, ...,field99). I wanted to count the non-empty values of each field so I wrote a simple php script with a for loop as below:
for($i = 1; $i <= 99; $i++)
{
$sqlstm = "SELECT COUNT(field$i) FROM table3 WHERE field$i IS NOT NULL AND field$i <> '';";
$r = #mysqli_query($dbc, $sqlstm);
if($r)
{
while($row = #mysqli_fetch_array($r))
{
echo "<p>$row[0]</p>\n";
}
}
else
{
echo "field $i error: " . mysqli_error($dbc);
}
}
But the loop stopped after showing four values (field1 to filed4) and no error message. I do have all 99 fields with data in table3 and I could run the query manually for any field. Could this due to browser timeout?
Can someone help me? Thanks.
$sqlstm = "SELECT COUNT(field$i) FROM table3
you are selecting the columns here, your table has 99 rows but apperantly only 4 columns
what you could better do is
$sqlstm = "SELECT * FROM table3 WHERE (column name) IS NOT NULL";
$count = 0
for($sqlstm as $one) {
$count = $count + 1;
}
echo($count);
or something along those lines

PHP array for loop

I want to show the array value $result[] from the for loop calculation. However, it shows me nothing on the page. Is there is anything wrong in the below code?
$sql= "SELECT * FROM items where itemID =3 ";
$result1= mysql_query($sql) or die (mysql_error());
while ($row= mysql_fetch_array($result1)){
$quantity[] = $row ['quantity'];
$month[] = $row ['month'];
}
$alpha = 0.3;
for($i = 1; $i > 12; $i++){
$result[$i] = ($quantity[$i] - $result[$i-1]) * $alpha + $result[$i-1];
}
foreach ($result as $key => $value ){
echo "$value";
}
Your for loop has an error. You have
for($i = 1; $i > 12; $i++)
but it should be
for($i = 1; $i < 12; $i++)
This is not directly the answer to your question, but there are few things that hasn't been mentioned that concern the way you query and process your data:
Your SELECT statement doesn't have specific order specified. Since order of records is not preserved you can get records out of correct order and get invalid calculations. Use ORDER BY (e.g. ORDER BY month) or make use of month values and extract exactly previous month's value from array(s) (if it is what you're doing in your code).
Your current code relies on the fact that the resultset from DB will contain (at least) 12 records. If for some reason it will produce less records your for loop will brake.
It's uncertain from the information in the question but it looks like you might need a year in your query unless the table contains records only for one year.
Now, you can calculate the whole thing on DB side with a query like this
SELECT i.month,
COALESCE((i.quantity - p.quantity) * 0.3 + p.quantity, 0) value
FROM items i LEFT JOIN items p
ON i.itemID = p.itemID
AND i.`year` = p.`year`
AND i.month = p.month + 1
WHERE i.itemID = 3
AND i.`year` = 2013
ORDER BY month
SQLFiddle
That's assuming (and I'm not sure about that) you actually need to read previous month's quantity values for your calculations and month column is of integer type
There is an obvious flaw in the logic. You try to get the $i index form $quantity. However, you can't be sure $quantity will have this index.
Supposing that itemId is not the primary key, I would do something like this:
$sql = "SELECT * FROM `items` WHERE `itemID` = 3";
$result1= mysql_query($sql) or die (mysql_error());
while ($row= mysql_fetch_assoc($result1)){
$quantity[] = $row ['quantity'];
}
$alpha = 0.3;
$i = 1
foreach ($quantity as $elem) {
if ($i >= 12)
break;
$result[$i] = ($elem - $result[$i-1]) * $alpha + $result[$i-1];
$i++
}
foreach ($result as $value ){
echo $value;
}

Query Multiple Conditions

I am keeping track of a few things on my site and im using a lot of queries because they need different conidtions
for example
$example = mysql_query("SELECT column FROM table WHERE column = 'Value1'");
$example_row = mysql_num_rows($example);
$example1 = mysql_query("SELECT column FROM table WHERE column = 'Value2'");
$example_row1 = mysql_num_rows($example1);
And so on, the value is always different so im having trouble finding a way to make this in to one query where i could still get different rows count for different values, is it possible?
I could test the row to see if it matches the value
if ($row == 'value'){
}
Multiple times but it still seems bad
Use IN()
SELECT column FROM table WHERE column IN('Value1', 'Value2');
I believe you want the count per value:
$values = ["value1", "value2", ...];
$query = "SELECT ";
for($i = 0; $i < count($values); $i++)
{
$query .= "SUM(IF(column = '$values[$i]')) AS v$i";
if($i != count($values) - 1)
$query .= ","; //Only add ',' if it's not the last value
$query .= " "; //We need the spaces at the end of every line
}
$query .= "FROM table";
//Let mysql do its work, run the query etc., store the resultset in $row;
Now you can dynamically iterate through the resultset:
$results = [];
for($i = 0; $i < count($values); $i++)
{
$string = "v"+ $i;
$results[] = $row[$string];
}

Categories