Multidimensional Array insert into Mysql rows - mysql

I have an Array (twodimensional) and i insert it into my database.
My Code:
$yourArr = $_POST;
$action = $yourArr['action'];
$mysql = $yourArr['mysql'];
$total = $yourArr['total'];
unset( $yourArr['action'] , $yourArr['mysql'] , $yourArr['total'] );
foreach ($yourArr as $k => $v) {
list($type,$num) = explode('_item_',$k);
$items[$num][$type] = $v;
$pnr= $items[$num][pnr];
$pkt= $items[$num][pkt];
$desc= $items[$num][desc];
$qty= $items[$num][qty];
$price= $items[$num][price];
$eintragen = mysql_query("INSERT INTO rechnungspositionen (artikelnummer, menge, artikel, beschreibung,preis) VALUES ('$pnr', '$qty', '$pkt', '$desc', '$price')");
}
I get 5 inserts in the Database but only the 5th have the informations i want. The firsts are incomplete.
Can someone help me?
Sorry for my english.

check if You have sent vars from browser in array (like
input name="some_name[]" ...
also You can check, what You get at any time by putting var_dump($your_var) in any place in script.
good luck:)

You probably want to have your query and the 5 assignments above that outside of the foreach. Instead in a new loop which only executes once for every item instead of 5 times. Your indentation even suggests the same however your brackets do not.
Currently it is only assigning one value each time and executing a new query. After 5 times all the variables are assigned and the last inserted row finally has everything proper.
error_reporting(E_ALL);
$items = array();
foreach($yourArr as $k => $v) {
// check here if the variable is one you need
list($type, $num) = explode('_item_', $k);
$items[$num][$type] = $v;
}
foreach($items as $item) {
$pnr = mysql_real_escape_string($item['pnr']);
$pkt = mysql_real_escape_string($item['pkt']);
$desc = mysql_real_escape_string($item['desc']);
$qty = mysql_real_escape_string($item['qty']);
$price = mysql_real_escape_string($item['price']);
$eintragen = mysql_query("INSERT INTO rechnungspositionen (artikelnummer, menge, artikel, beschreibung,preis) VALUES ('$pnr', '$qty', '$pkt', '$desc', '$price')");
}
Switching on your error level to E_ALL would have hinted in such a direction, among else:
unquoted array-keys: if a constant of
the same name exists your script will
be unpredictable.
unescaped variables: malformed values
or even just containing a quote which
needs to be there will fail your
query or worse.
naïve exploding: not each $_POST-key
variable will contain the string
item and your list will fail, including subsequent use of $num

Related

Loop in column name MYSQL

I am using MYSQL.My table contains column name as Revenue2000,Revenue2001,Revenue2002,....,Revenue 2016,Revenue 2017
Traditional way(to select all column manually):
select Revenue2005,
Revenue2006,
Revenue2007,
Revenue2008,
Revenue2009,
Revenue2010
from table_name
Desired Way:
I want to write a Dynamic select statement .There should 2 variables "start" and "end" so that i can make it dynamic.User has the option to specify the starting year and ending year and can view the desired result.
In above case, Start year =2005
End Year=2010
Yes, it's bad database design, and the best answer would be "don't do this at all, just fix your table." Unfortunately, sometimes you're stuck with something someone else made, and can't change it for whatever reason, but you still need to accomplish something (welcome to my life). I would do it like this:
Get the years from user input and convert them to integers in case someone enters something silly/naughty. Don't depend on client-side validation. Prepared statements won't help you here because these will be used as parts of column names.
$start = (int) $_POST['start'];
$end = (int) $_POST['end'];
Do a quick sanity check to make sure that the range makes sense and should work with what's in your database.
if ($start > $end
|| $start < $lowest_year_in_your_db
|| $end > $highest_year_in_your_db) {
// quit with error
}
Then you can generate a list of columns to use in your query. Here's one way with range and array_map, but you could also just build a string with a for loop.
$columns = implode(', ', array_map(function($year) {
return "Revenue$year";
}, range($start, $end)));
$sql = "SELECT $columns FROM table_name";
Theoretically, the worst thing that should be able to happen with this is that you'd get a column that didn't exist, and your query would fail.
But really, if you have any choice about it, don't do this. Normalize your database as people have stated in the comments, or find whoever keeps adding more year columns to the database and make them do it.
As already pointed out the database design is horrible. You should really normalize it, it's worth the effort.
However if that is not possible at the moment the follow code should do exactly what you need:
// Connect to DB
$mysqli = new mysqli("localhost", "USERNAME", "PASSWORD", "DATABASE");
// Get column names
$columns = $mysqli->query('SHOW COLUMNS FROM revenue')->fetch_all();
$columnNames = array_column($columns, 0);
// Extract years from column names
$years = array_map(function($columnName) {
return (int) substr($columnName, -4);
}, $columnNames);
// Get max and min year
$maxYear = max($years);
$minYear = min($years);
// Input year start and end
$start = (int) $_POST['start']; // User-input
$end = (int) $_POST['end']; // User-input
// Avoid wrong inputs
if($start > $end || $start < $minYear || $end > $maxYear) {
die('Error');
}
// Create the SQL-query
$selectColumns = [];
for ($i = $start; $i <= $end; $i++) {
$selectColumns[] = "revenue" . $i;
}
$queryString = "SELECT " . implode(", ", $selectColumns) . " FROM TABLE";
// Run the query
// ...

echo a variable from a multidimentional array outside a function

The code below works for a string value but not when I try to access the variable directly.
The data being accessed is a table at http://webrates.truefx.com/rates/connect.html?f=html
My code strips it of tags and put it in an array $row0
And puts it in a function. But I can't get it out. The function is simplified for this question. I intend to concatenate some of the variables inside the function once I find out what I'm doing wrong.
$row0 = array();
include "scrape/simple_html_dom.php";
$url = "http://webrates.truefx.com/rates/connect.html?f=html";
$html = new simple_html_dom();
$html->load_file($url);
foreach ($html->find('tr') as $i => $row) {
foreach ($row->find('td') as $j => $col) {
$row0[$i][$j]= strip_tags($col);
}
}
myArray($row0); //table stripped of tags
function myArray($arr) {
$a = 'hello'; //$arr[0][0]; HELLO will come out but not the variable
$b = $arr[1][0];
$r[0] = $a;
$r[1] = $b;
//echo $r[1]; If the //'s are removed one can see the proper value here but not outside the function.
return $r;
}
$arrayToEcho = myArray($arr);
echo $arrayToEcho[0]; // will echo "first"
I have tried all the suggestions from here:
http://stackoverflow.com/questions/3451906/multiple-returns-from-function
http://stackoverflow.com/questions/5692568/php-function-return-array
Suggestion appreciated please and more info available if required. Thank you very much for viewing.
You need to get the innertext of $col in your loop. Like this:
$row0[$i][$j]= $col->innertext;
The next thing is:
myArray($row0);
This call will correctly return the parsed array; try echoing it and you'll see. But when you do this:
$arrayToEcho = myArray($arr);
...you're referencing to $arr which is a local variable (a parameter, actually) inside your function myArr. So what you probably meant was this:
$arrayToEcho = myArray($row0);
Hope this helps!
UPDATE
Look, I show you what happens when you call a function:

How to recursively get an array of child ids in Modx Revolution without using getChildIds

getChildIds can be very slow if running it against a large set of resources, so I am trying to write a query and some code to get all the child ids faster.
However I am getting different results from getChildIds & my script.
Can anyone see why these would be yielding different results?
Method using getChildIDs:
$parentDepth = isset($scriptProperties['parentDepth']) ? $scriptProperties['parentDepth'] : 5;
$parents = explode(',', $parents);
$children = array();
foreach ($parents as $parent){
$ids = $modx->getChildIds($parent,10,array('context' => 'web'));
foreach($ids as $id){
$children[] = $id;
}
}
echo ' number of children = ' . count($children);
method using queriees & a loop:
$comma_separated = implode(",", $parents);
$sql = "SELECT `id` from modx_site_content where `parent` IN (".$comma_separated.") and published = 1 and isfolder = 0 and deleted = 0 and hidemenu = 0;";
$results = $modx->query($sql);
$mychildren = array();
while ($row = $results->fetch(PDO::FETCH_ASSOC)) {
$mychildren[] = $row['id'];
}
for($i=0; $i <= 10; $i++){
$comma_separated = implode(",", $mychildren);
$sql = "SELECT `id` from modx_site_content where `parent` IN (".$comma_separated.") and published = 1 and isfolder = 0 and deleted = 0 and hidemenu = 0;";
$results = $modx->query($sql);
while ($row = $results->fetch(PDO::FETCH_ASSOC)) {
$mychildren[] = $row['id'];
}
}
echo ' number of children = ' . count($mychildren);
The getChildIDs method takes nearly 1.5 seconds to run and gives about 1100 results
The SQL/script method runs un under 0.1 second and gives 1700 results.
Either I'm not appending the child ids to the array properly ~or~ maybe getChildIDs is filtering out some other results?
does anyone have any clues as to what could be happening here?
You can try to use built-in method of pdoFetch.
$pdo = $modx->getService('pdoFetch');
$ids = $pdo->getChildIds('modResource', 0);
print_r($ids);
It also recursive, but can be better in some situations.
Of course, you need to install pdoTools from the repository first.
Looking at the code again, the discrepancy in results is pretty obvious now. I'm appending results to the child id array, it's inserting duplicates since one parent can have many children.
the solution to avoid duplicates:
$mychildren[$row['id']] = $row['id'];
getChildIds - is recursive, so it slower by default.

Show missing dates inside loop even if they don't exist inside MYSQL

I have following mysql query
SELECT count(order_id), date FROM tbl_order WHERE campaign_status = 'In Progress' or campaign_status = 'Pending' GROUP BY DATE_FORMAT(date,'%d %b %y')
and then following loop
<?php do { ?>
['<?php echo $row_chartData['date']; ?>', <?php echo $row_chartData['count(order_id)']; ?>],
<?php } while ($row_chartData = mysql_fetch_assoc($chartData)) ?>
this loop is used to create data for my chart. Now the problem is that there are certain days that users dont make orders in my store so those dates are not stored inside database, so when I loop trough those dates are not showed in above results and inside the chart.
The question I have, is there any way to show those missing dates in loop above even if they dont exist inside mysql database.
Thanks for help.
Well, in this case, create a temporary array based on the date range, e.g. if you want to show the graph from May 1, to May 31.
Loop from 1 to 30,
set $data[i] = 0;
Now loop through the db records and set
$data['date'] = $row['count']
Yes.
Firstly make $row_chartData as array instead of a mysql_result.
1) find the min date in the range or whichever date you want to start with
function _getDate($row) {
return $row['date'];
}
$dates = array_map('_getDate', $row_chartData);
$minDate = min($dates);
2) find the max date in the range or whichever date you want to end with
$maxDate = min($dates);
$dateRangeArray = array();
$date = $minDate;
while($date < $maxDate) {
$dateRangeArray[] = $date;
$date = date('Y-m-d', strtotime($date . ' +1 day'));
}
3) make the key of each element in your $row_chartdata array be the value of the date index
foreach($row_chartData as $key => $row) {
$row_chartData[$row['date']] = $row;
unset($row_chartData[$key]);
}
4) iterate over each of the days in the range and match that date to the index in your $row_chartdata array
foreach($dateRangeArray as $date) {
if(isset($row_chartData[$date])) {
//do whatever
}
}

how use mysql_data_seek with PDO?

I want use mysql_data_seek with PDO from google search I found that it should looks like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
however it's not work, what I do wrong?
this is my code:
$query = "SELECT name,age FROM users";
$q = $db->prepare($query);
$q->execute();
$q->setFetchMode(PDO::FETCH_ASSOC);
$arrayData = $q->fetchAll();
foreach ($arrayData as $row){
echo $row['name'] ." ";
echo $row['age'] ."<br>";
}
$result = $q->fetch(PDO::FETCH_OBJ,PDO::FETCH_ORI_ABS,4);
var_dump($result);
I just want get the 5th row in object form from the last run query. I don't want run this query again (as some guys told me) I just want the results from sql buffer.
the var_dump result is: bool(false)
any ideas?
EDIT:
thanks for your answers and sorry but maybe I don't explain myself as well. I like the trick with JSON but the point is that the 5th row is example. I just want use the result of the query from the buffer with PDO exactly as I did it with mysql_data_seek in regular mysql (change the cursor). is it possible? I like all the tricks but that not what I look for.
the PDO 'cursor' default is PDO::CURSOR_FWDONLY that means that cursor can't back to zero like it happens with mysql_data_seek to allow cursor back to zero it necessary define use 'scrollable cursor'
example:
$db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
before use it like this:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
$result = $arrayData[4];
is all you need.
If you want the 5th row result you can do like this:
$result = json_decode(json_encode($arrayData[4]), FALSE);
var_dump($result);
or something like this:
$object = new stdClass();
foreach ($array as $key => $value)
{
$object->$key = $value;
}
Just curious! why do you need the object form?
EDIT (this will give the object form of the 5th row):
$index = 0;
$fifthRow = new stdClass();
while($row = $q->fetch())
{
if($index++==4)
$fifthRow = json_decode(json_encode($row), FALSE);
}
You could do it like this:
$c = 1;
$saved=null;
while($row = $q->fetch()){
if($c==4){
$saved = clone $row;
};
$c++;
somethingelse;
}
$saved will then contain the 4th element as an object with almost no extra overhead calculations.