Insert cloned elements in just one query - php

I make a cloned element from the original, also increase the name value like this:
Original
name="UM"
Cloned elements
name="UM1"
name="UM2"
name="UM3"
And I need to insert the data from that cloned elements, I thought make like this:
$UM1 = $_POST['UM1'];
$DS1 = $_POST['DS1'];
$Cant1 = $_POST['Cant1'];
$FU1 = $_POST['FU1'];
$query = 'INSERT INTO TABLE
VALUES (\''.$UM1.'\',\''.$DS1.'\',\''.$Cant1.'\',\''.$FU1.'\')';
mysql_query($query) or die(mysql_error());
With every element, but is so much code, exist any way to make this diferent, something like the css selectors select[id^="UM"]?
Many Thanks.
Fiddle
Solution:
$rows = array();
$i = 1;
while (isset($_POST["UM$i"])) {
$rows[] = array($_POST["UM$i"], $_POST["DS$i"], $_POST["Cant$i"], $_POST["FU$i"]);
$i++;
}
foreach ($rows as $row) {
$query = 'INSERT INTO papeleria (id, UM, DS, Cant, FU) VALUES ("","'.$row[0].'","'.$row[1].'","'.$row[2].'","'.$row[3].'")';
mysql_query($query) or die(mysql_error());
}

You can just use a for loop
$rows = array();
$i = 1;
while (isset($_POST["UM$i"])) {
$rows[] = array($_POST["UM$i"], $_POST["DS$i"], $_POST["Cant$1"], $_POST["FU$1"]);
$i++;
}
foreach ($rows as $row) {
$query = "insert into table values ('$row[0]', '$row[1]', '$row[2]', '$row[3]')";
mysql_query($query) or die(mysql_error());
}

No there is no such method but you dont need to escape the ' .
$query = "INSERT INTO TABLE VALUES ('$UM1','$DS1','$Cant1','$FU1')";
this should work perfectly

Related

array_sum returning the sum of values as string

This seems like it should be really straightforward, but I keep getting unexpected output. I'm trying to access specified rows in a SQL database which each contain a numerical value and then calculate the sum of those values. PHP is concatenating the values as if they were strings even after I've set the datatype of the values to float. My code:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
$population_value = is_array($population_value) ? $population_value : array($population_value);
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I have also tried:
$total = array("");
foreach($population_value as $value){
floatval($value);
array_push($total, $value);
echo $value;
}
echo array_sum($total);
My output is always something like: 100002000030000
with 10,000 20,000 and 30,000 being the values of each population.
I've successfully calculated sums using foreach with values that weren't retrieved from MySQL.
What is going on here?
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
//This is actually rewriting the array or NOT adding the value to it.
$population_value = is_array($population_value) ? $population_value : array($population_value);
//ok, so you're going to repeatedly output this?
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I think what you want is this:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
$population_value=array(); //Initialize the array so we can just add to it.
while($row = mysqli_fetch_assoc($result)) {
$population_value[]= intval($row['population_value']); //Just making sure we get a number.
echo end($population_value); //We could output the row again, or just grab the last element of the array we added.
}
//Now that the array is fully populated and we've made sure it's only numbers, we output the grand total.
echo array_sum($population_value);
First, don't initialize the array with an empty string. Do this instead:
$total = array();
or with the new style:
$total = [ ];
Second, rewrite the floatval thing like this:
array_push($total, floatval($value));
That should fix it...

Fetch all fields from all rows - MYSQL

I understand this could appear alarming but bear with me.
I need to echo every field in every row in a table.
This is only an example - I have removed the HTML wrapped around it to improve readability.
$a = 1;
while ($a <= $count_rows) {
$query = "SELECT col1, col2 etc.. FROM table WHERE `id`='$id'";
$result = mysqli_query($con, $query);
$i = 1;
while($i <= $count_fields) {
$row = mysqli_fetch_array($result, MYSQL_NUM);
echo "$row[$i]";
$i++;
}
$a++;
$id = $a;
}
This only outputs the first field of every row? Why?
If I echo $row[2] I get nothing!
If I echo $row[2] I get nothing!
because it's actually third item
and there is some strange code interfering with $i variable
Anyway, to get every column from every row ou need a code like this
$query = "SELECT * FROM table";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_row($result)) {
foreach ($row as $index => $value) {
echo "$index => $value, ";
}
echo "<br>\n";
}

getting results of SQL query

I've seen there there are numerous ways to put the results of a SQL query into usable format (that is, variables).
If I have a targeted SQL query that I know will be returning a set of expected values, lets say querying a customer number to pull data, city, state, first and last name, etc..
Code example follows:
$example = '50';
$result = mysql_query("SELECT * FROM customers WHERE customer_ID = '$example'",$db);
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $col => $val) {
if ($col == 'firstname') {
$customerfirstname = $val;
}
}
}
or another way:
$result = mysql_query("SELECT * FROM customers WHERE customer_ID = '$example'",$db);
$myResultArray = array();
while ($row = mysql_fetch_assoc($result))
$myResultArray = $row;
foreach ($myResultArray as $val) {
$customerfirstname = $val['firstname'];
}
That's just two that I could think of.
Is one of the above methods preferable over the other? If so, why?
Is there an alternate method that is even more efficient than either of these?
Neither are preferred.
The foreach's are superfluous.
Since you know the fieldnames you need, you can just do:
while ($row = mysql_fetch_assoc($result)) {
$customerfirstname = $row['firstname'];
}
If you do need to apply a conditional for some reason, you can test for the field's existence in the array:
while ($row = mysql_fetch_assoc($result)) {
if (isset($row['firstname'])) {
$customerfirstname = $row['firstname'];
}
}
Finally, since you appear to be selecting by primary key, the while loop is also unnecessary:
if ($row = mysql_fetch_assoc($result)) {
$customerfirstname = $row['firstname'];
}
I have used the first example that you posed in every website I have done that requires a database and it hasn't failed me yet. As far as if one is better than the other I'd say no. It's just a matter of taste.
There are many ways. Here's a quick one, but I would prefer to set it up using a DTO and accessing it that way... this will work though for your question.
$query = "SELECT first_name, last_name, city FROM customers WHERE customer_id = '$example'";
$result = mysql_query($query);
// If you are expecting only one row of data, then use this:
list($first_name, $last_name, $city) = mysql_fetch_row($result);
//several rows:
while(list($first_name, $last_name, $city) = mysql_fetch_row($result)){
echo $first_name;
}
I seem to be missing something...
Why not this?
$result = mysql_query("SELECT * FROM customers WHERE customer_ID = '$example'",$db);
while ($row = mysql_fetch_assoc($result)) {
$customerfirstname = $row['firstname'];
}
In the first example?

Generating variables from db content?

I am querying a database to get 6 values in my params table suing this;
$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
$param = $row['value'] ;
}
is this right, if so is their away i can add one to the variable name each time round so i get $param1, $param2....
I dont want to have to send a query to the database for each param, is it possible to get them all like this?
The simpliest way is to use an array:
$result = mysql_query("SELECT * FROM params");
$param = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
$param[$i] = $row['value'] ;
$i++;
}
Than you get $param[0], $param[1], ...
You can create variable names like this:
${'var'.1}
${'var'.'1.cat'}
${'var'.$x}
${$y.$x}
and so on.
This seems like a design flaw. But what you can do is:
$count = 1;
$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
$paramname = 'param' . $count++;
$$paramname = $row['value'] ;
}
You may find the list function useful - http://php.net/manual/en/function.list.php
list($param1,$param2,$param3,$param4,$param5,$param6) = mysql_fetch_row($result);
Probably more use when using descriptive variables, just a thought.

How to save tags/keywords from array to database with php?

I saw this question: how to save tags(keywords) in database?
Good answer for how the database should be structured. But which way is best to do the saving process in php? A process that handles both adding and deleting.
The keywords are posted as an array.
Edit:
The current code look like this:
<?php
$new = explode(',', $_POST['tags']);
$query = mysql_query("SELECT * FROM pages_tags WHERE page_id = '".$page_id."'") or die(mysql_error());
while ($row = mysql_fetch_array($query))
{
$old[] = $row['tag'];
}
$tags_to_add = array_diff($new, $old);
$tags_to_remove = array_diff($old, $new);
if (is_array($tags_to_add))
{
foreach ($tags_to_add as $add_tag) { $insert_tags[] = "('".$add_tag."', '".$page_id."')"; }
$sql_insert_tags = "INSERT INTO pages_tags (tag, page_id) VALUES ".implode(',', $insert_tags);
mysql_query($sql_insert_tags) or die(mysql_error());
}
if (is_array($tags_to_remove))
{
foreach ($tags_to_remove as $remove_tag) { $delete_tags[] = "('".$remove_tag."')"; }
$sql_delete_tags = "DELETE FROM pages_tags WHERE page_id = '".$page_id."' AND tag IN (".implode(',', $delete_tags).")";
mysql_query($sql_delete_tags) or die(mysql_error());
}
?>
I propose to select current tags and after you can do:
$tags_to_add = array_diff($new, $old);
$tags_to_remove = array_diff($old, $new);
After that you write 2 trivial queries: one to bulk insert and one to delete.

Categories