PHP foreach not inserting whole array into mysql table - php

Hi I have created a simple foreach loop which is looping through an array and inserting the data into my db table. The problem I am having is it is only inserting 130 rows into my database even though the array contains 196.
Here is my code:
foreach ($currencyArray as $currency) {
if (count($currency) > 1) {
$currency_table = $db->prepare('
INSERT INTO currency_name (symbol, name, btc_value)
VALUES (:name, :symbol, :btc_value)
');
$currency_table->bindParam(':name', $currency[0]);
$currency_table->bindParam(':symbol', $currency[1]);
$currency_table->bindParam(':btc_value', $currency[2]);
$currency_table->execute();
}
}
I have made sure it isnt the if statement causing the problem. I added a count to inside the if statement and this count 197 records which is the amount of rows I am expecting in my db table, but it is only storing 130 rows?
If you also believe there is a faster way of inserting the array into the db table please feel free to share :)

I found out what the error was it, it was my mistake some of the names I am inserting into the database are longer than I have allowed

Related

multiple foreach loops for different variables?

foreach ($textAr as $BachelorsDegrees)
{
foreach ($textArCert as $Certifications)
{
foreach ($textArDip as $Diplomas)
{
foreach ($textArAD as $AssociateDegrees)
{
foreach ($textArMD as $MastersDegrees)
{
foreach ($textArDD as $DoctorateDegrees)
{
foreach ($textArSD as $SpecialDegreePrograms)
{
what would be the best way to make the above code work (it's just a snippet of the entire code)? Each variable, for example $BachelorsDegrees, is a textarea box in the HTML form. I am trying to insert values from each textarea box into the database in individual rows. I got it working for one textarea box, but how to make it work for multiple textarea boxes?
Was thinking of doing an if else statement and an INSERT and UPDATE sql statement so that when one foreach loop worked, it would INSERT data into the database, then the loop would stop, then an else statement would go for the next foreach loop and an UPDATE query would update the next column for the same product instead of inserting. If I did multiple INSERT queries, I would be creating more rows for each variable, which I don't want. More rows for the values on each variable, but not rows for the actual variable. Each variable represents a column.
For example,
When the values from the BachelorsDegrees textarea get inserted into its column, the next loop will run (Certifications) into the next column. So I was thinking an UPDATE query would be effective. That way I don't have NULLS in every column.
If you have equal number of inputs for all the fields(Bachelorsdegree,certifications,etc), then you can take count of one input field into equation.e.g
$totalinputs=count($textAr);
for($i=0;$i<$totalinputs;$i++){
$bachelordegree=$textAr[$i];
$certificate=$textArCert[$i];
$diploma=$textArDip[$i];
.....
.....
//use above stored variables to insert/update into your respective table.
}

Why would `mysqli_fetch_assoc` be returning an empty object?

I'm having to debug some legacy PHP code and I've hit a real puzzler.
A method loops through each row of a MySQL table and adds the row to an array.
Unfortunately, the method is returning a completely empty object, so the HTTP response is of zero-length.
It seems that one particular row in the MySQL table is causing this issue, when mysqli_fetch_assoc is called. I've narrowed it down to row 1251 by adding in the test code below.
$counter = 0
while ( $row = mysqli_fetch_assoc($findInfo) ) {
// My Debug Test Code: bail out and return row 1251
if ($counter == 1251)
return $row; // this returns a populated array for all rows except 1251, which is blank
// Add the row to our array
array_push($rowArray, $row);
$counter = $counter + 1
}
// Finally, do something with all the rows
return $rowArray
If I generate a .CSV dump of the data table, the data looks fairly innocuous - row 1251 is the line beginning 94340 in the snippet below:
94339,"Hills Coaches (Wolverhampton)",,,,,,,,,,,,,,,,
94340,"Hinckley Bus",,"via contact form at www.arrivabus.co.uk/contact-arriva/  ","01455 239329",,,"5 Jacknell Road, Dodwells Bridge Industrial Estate, Hinckley LE10 3BS",,,,,,,,,,www.arrivabus.co.uk/hinckleybus/#http://www.arrivabus.co.uk/hinckleybus/#
94341,Hirethisbus.com,,,,,,,,,,,,,,,,
What might cause mysqli_fetch_assoc to apparently 'bail out' in this way and return nothing? How would I even debug this?
The MySQL row contained some unprintable characters, determined by connecting to the server via the MySQL client and running a manual SELECT on the row.
`SELECT ColumnName FROM TableName WHERE Id = SomeID`
======+==========+===========
ColumnName +========+========
=============================
http://some.site.com/??
=============================
The two question marks were the giveaway.
Still no idea why mysqli_fetch_assoc was unhappy with it, though.

multiple queries in one mysql connection fail to be run with php

Here is a part of my php code:
foreach ($value->ahkam as $k => $v){
echo $v->id."\n";
//Save into db one hokm
$addHokm = "INSERT INTO qm_hokm (hokm_id, type, tooltip, line, x1, y1, x2, y2, radius, XOrigin, YOrigin, page_id)
VALUES ($v->id,$v->type,'tooltip',0,$v->x1,$v->y1,$v->x2,$v->y2,$v->r,$v->XOrigin,$v->YOrigin,$pageNumber)";
if(!mysqli_query($con, $addHokm))
echo "Failed to insert into db...".$v->id."\n";
}
In fact, I am fetching a json structure sent by an ajax request from a client.
I have many values in $value->ahkam but the problem is that only the first query is run and the others give me the error msg. Any help plz
UPDATE:
the result of echo is:
0
1
Failed to insert into db...1
2
Failed to insert into db...2
As you see, the hokm number 0 is added but not the others, I need to mention also that $pageNumer is a foeign key
The problem is in your foreign key, it must not be unique. Like that, you can add multiple entries for one page_id. I hope it is the correct answer:)
Based on your comments, it appears that your query is inserting a duplicate value for the page_id value, which appears to be set as a field that cannot have duplicate values. According to your query, you're using $pageNumber for that field, but I don't see it changing in your loop. You either need to get rid of the constraint preventing you from using the same value or make sure that $pageNumber has a value that isn't being used already.

single sql database entry with muliple values into an array

the script querys database and retrieves a single entry that has mulitple numbers
SELECT jnum from database where x = y
output = 11111,22222,33333,44444
So i explode that on , and get $variable[0] = 11111 and $variable[1]= 22222
What i want to do is perform a query on another table using each of those numbers (numbers will be different each time and there may be any number of numbers).
is there a way to structure a foreach for each entry in the array or a while loop that counts so that i can query the database for each of the values i get from output above.
i don't know if i am conveying what 'im trying to do here very clearly so i apologize in advance.
i get a single entry for the database table and it contains a string (11111,22222,33333)
i explode on , and get the array variable[]
there will not always be 3 entries sometime there could be 5 or 7 or 10 or 1 but each one will be unique.
but for each value i want to query a db table and retrieve all the rows that have that single number($variable[]) as an entry.
Not sure if a loop count or a foreach statement would work. any ideas?
Well assuming these are values in a single column there is no need to look you can use WHERE ... IN:
SELECT * FROM the_other_table WHERE some_col IN ('11111','22222','33333')
Check out foreach loops - http://php.net/manual/en/control-structures.foreach.php
foreach ($variable as $value) {
$myquery = "some query using $value";
// then execute your query
}

INSERT: inserting multiple rows at once, or one by one?

I'm inserting multiple rows in a table, and I get this message:
MySQL server has gone away
My Query:
INSERT INTO table
(a,b,c,d,e,f,g,h,i,j,k)
VALUES(1,2,3,4,5,6,7,8,9,10,11),(1,2,3,4,5,6,7,8,9,10,11), ...
ON DUPLICATE KEY UPDATE
c=VALUES(c),
d=VALUES(d),
e=VALUES(e),
f=VALUES(f),
g=VALUES(g),
h=VALUES(h),
i=VALUES(i),
j=VALUES(j)
Is it because I stuffed too many values inside a single query? (There are like 5000 pairs of values from a array which I implode with ,).
If this is the reason - then should I insert each row one by one? Is it slower than inserting them all at once?
The PHP code:
foreach($data as &$entry)
$entry = "('".implode("','", array(
$entry->ID,
addslashes($entry->field_1),
addslashes($entry->field_2),
...
))."')";
$data = implode(',', $data);
$query = "... VALUES{$data} ON ..."
$data is a array of STD type objects...
edit again :)
So I tried splitting my $data into smaller arrays of 100 elements each:
$data_chunks = array_chunk($data, 100);
foreach($data_chunks as $data_chunk)
insert_into_db($data_chunk);
and it works, I don't get that error anymore...
So that means the issue was the very long query string...
Now I'm even more confused:
Is there a length limit of the query, or maybe PHP arguments in general?
Is there any difference between inserting row by row than inserting multiple rows? Is it worth the array_chunk() ?
it could be that your query is taking too long to complete, mysql times out and closes the connection. You can alter the system variables to wait longer.
http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
I think your problem is with *max_allowed_packet*, although the error seems to point in different direction. Try doing as suggested here: http://dev.mysql.com/doc/refman/5.5/en/packet-too-large.html
Or, before making any changes to mysql configuration, simply strlen() your query and find out how long(in bytes) it actually is.

Categories