MySQL insert inside foreach only being called once - php

I have an array $alert_note. I iterate through a loop and fill it up with a few strings:
$n = 0;
$alert_note = array();
$results = array();
while($row = mysqli_fetch_assoc($query)){
//some code in here populates the $results[$n] array with results from $row
$thisnote = "<b>Location alert</b><br>
Alert ID: {$results[$n]['alert-id']}<br>
Start: {$results[$n]['start-formatted']}<br>
End: {$results[$n]['end-formatted']}<br>
Radius: {$results[$n]['radius-km']} km<br>
Distance: {$results[$n]['distance-km']} km<br>
<ul>\n";
//$results[$n]['data'] is a nested array, so iterate through it:
foreach($results[$n]['data'] as $name => $data){
$thisnote .= "<li>$name: $data</li>\n";
}
$thisnote .= "</ul>";
$alert_note[$n] = $thisnote;
$n++;
}
Then I call a foreach function:
foreach($alert_note as $alert_note_contents){
error_log("Note: $alert_note_contents");
mysqli_query($dblink, "INSERT INTO `incident_events` (`incident`, `data`, `time`, `operator`) VALUES ('$incident', '$alert_note_contents', '$now', '$operator')");
}
Each string in $alert_note shows up as expected in the PHP error log, but only the last one is inserted into the MySQL table. No PHP errors are being thrown. Any ideas why this may be?

plz before foreach($alert_note as $alert_note_contents){
do this so i can get the error
var_dump($alert_note );
and do this plz so i can see if there is any error ind db
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{ die("Connection failed: " . $conn->connect_error); }
$sql = "INSERT INTO incident_events (incident, data, time, operator) VALUES ('$incident', '$alert_note_contents', '$now', '$operator')";
if ($conn->query($sql) === TRUE)
{ echo "New record created successfully"; }
else { echo "Error: " . $sql . "<br>" . $conn->error; }
$conn->close();

Related

Codeigniter XML Datafeed to Multiple (MYSQL Tables)

goodness.. it's been a quite a headache for me.
I'm trying to get variable SQL1, SQL2 and SQL3 to update different mysql tables.. but how on earth will SQL2 and SQL3's "product_id" fields, correlate with SQL1?
See 'id' in the insert sections in SQL2 and SQL3.. i'm not sure how to replace and grab this generated data into this sections without making more ugly code.
Also, if any of you have any idea how to make this easier, please help a fellow out here.. this looks pretty dirty to me.. surely there are better ways :(
// DB Settings
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Load data from XML file
$xml = simplexml_load_file("Datafeed.xml");
// Capture XML Data
foreach($xml->children() as $product) {
// Change stock wording
$stock = $product->stock;
if ($stock == 'yes') {
$stock = 'on';
} else {
$stock = 'off'; }
// Convert XML data and insert into MYSQL
$sql = "INSERT INTO testshop_products (product_id, product_name, product_type, product_price, product_status) VALUES ("echo $product->code;", "echo $product->cat;", "echo $product->price;","echo $stock;")";
$sql2 = "INSERT INTO testshop_product_details (product_id, product_color, product_image, details_status) VALUES ('id', "Generating...", "echo $product->img;","echo $stock;")";
$sql3 = "INSERT INTO testshop_spesifications (product_id, specs_meta, specs_details, specs_slug, specs_status) VALUES ('id', General, "echo $product->img;", general, "echo $stock;")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
if ($conn->query($sql2) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
if ($conn->query($sql3) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
write store procedure and inset all records and all table it will find.
store procedure like this
CREATE PROCEDURE `addJobApplicant`(IN XMLINPUT
text, OUT vresult VARCHAR(100))
BEGIN
DECLARE iCounter INT DEFAULT 1;
DECLARE maxCount INT;
SET vcompID=ExtractValue(XMLINPUT, '/ROOT/HEADER/COMPANYID[$iCounter]');
SET vjpID=ExtractValue(XMLINPUT, '/ROOT/HEADER/JOBID[$iCounter]');
insert command here
SET vresult = 'Successfully Inserted';
end

How can I use a for loop to insert data from a csv table to a sql database?

This is the sample csv file I'm using:
Column1,Column2,Column3
data1,data2,data3
data1,data2,data3
data1,data2,data3
data1,data2,data3
The purpose of my program is to insert this table into a php file via command line and insert the data into an SQL database. I'm using this project as a way of learning how to use MySql.
A csv file is taken and the data is then converted into an array or arrays. A database is then created and the data is supposed to be inserted into the table.
Instead of my data being inserted, I get only one row with null values.
<?php
/**
* Created by PhpStorm.
* User:
* Date: 6/16/2017
* Time: 11:32 AM
*/
$servername = "localhost";
$username = "pop-user";
$password = "pop-pw";
$database = 'popdb';
parse_str(implode('&', array_slice($argv, 1)), $_GET);
$file = array_map('str_getcsv', file($argv[1]));
// connecting to MySQL
$link = mysqli_connect($servername,$username,$password);
// check if connection completed
if ($link->connect_error) {
die("Connection failed: ". $link->connect_error);
}
//creating database
printf("Creating database...\n");
$dbcheck = mysqli_select_db($link, $database);
// if database doesn't exist, then one will be created
if (!$dbcheck) {
$sql = 'CREATE DATABASE '. $database;
if (mysqli_query($link, $sql)) {
echo "Database ". $database ." created\n";
}
else {
echo "Failed to create database:\n";
echo $link->error."\n";
}
}
printf("Creating table...");
//creating table to hold information
$sql = 'USE '. $database. ';';
printf("\r\n");
mysqli_query($link,$sql);
$sql2 = "CREATE TABLE popCensus (";
foreach ($file[0] as $rows) {
if ($rows != end($file[0]))
$sql2 .= "{$rows} varchar(33), ";
else
$sql2 .= "{$rows} varchar(33)";
}
$sql2 .= ");";
echo $sql2;
printf("\r\n");
mysqli_query($link,$sql2);
printf("Inserting data into table...\n");
$cnt = 1;
$sql3 = "";
//Not inserting data
foreach ( $file as $file[$cnt]) {
$sql3 = "INSERT INTO popcensus VALUES ( ";
foreach ($file[$cnt] as $rows) {
if ($rows != end($file[$cnt]))
$sql3 .= "{$rows} , ";
else
$sql3 .= "{$rows});";
}
printf($sql3);
printf("\n");
mysqli_query($link, $sql3);
$cnt++;
printf("cnt: ". $cnt."\n");
$sql3 = "";
}
printf("\nDone\n");
mysqli_close($link);
?>
edit: I'm able to parse the information into an arrays of arrays. the problem I'm having is trying to insert them into a table afterwards.
you need to use prepared statement inside the loop
Try checking the query for an error result inside the foreach loop.
if (false === mysqli_query($link, $sql3)) {
throw new Exception(mysqli_error($link));
}
Beyond that, you should really be using a prepare statement.

PHP > Invalid Argument supplied for foreach()

In short, I am trying to figure out what is wrong with my foreach statement. I have been trying to work on finding the error for over a day know and I'm running out of time. This program is supposed to parse a json array and post it up to a mysqli database.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$a = print_r(var_dump($GLOBALS),1);
echo htmlspecialchars($a);
$servername = "#";
$username = "#";
$password = "#";
$dbname = "#";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
echo "Connection Successful : ";
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Read JSON file
$jsondata = file_get_contents('scripts/AUDIT_DIR/report.json');
echo "JSON File Read : ";
// Convert and Loop
$item = json_decode($jsondata, true);
echo "JSON File Decoded : ";
foreach($item as $arr)
{
$id = $arr["id"];
$hostname = $arr["hostname"];
$ip = $arr["ip"];
$package = $arr["package"];
$publisher = $arr["publisher"];
$origin = $arr["origin"];
$version = $arr["version"];
$size = $arr["size"];
$sql = "INSERT INTO testtable(id, hostname, ip, package, publisher, origin, version, size)
VALUES ('10', '$hostname', '$ip', '$package', '$publisher', '$origin', '$version', '$size')";
if (mysqli_query($conn, $sql))
{
echo "New record created successfully : ";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
You likely have an invalid return from your json_decode() you can check this with a var_dump($item); after your json_decode()
In php json_decode() will return NULL if the json cannot be decoded or if the encoded data is deeper than the recursion limit. http://php.net/manual/en/function.json-decode.php
You need to properly guard for such a case that $item === null and not assume you will always get a valid return for your foreach() params.
Example showing your error happens when $item = null
https://3v4l.org/oNr8P

PHP split a string and insert in MySQL

I am using AJAX to send an array of values to a PHP page that will insert the data into MySQL database. The problem is that I am not sure how to split the data into 5 different veriables and loop to insert into DB.
AJAX Request:
Array:
[".testimonial", 1119, 316, 1663, 608, "#header", 723, 66, 1663, 608]
Posting the array:
Sending Array Parameters using " ; " to split.
clicks
.testimonial;1119;316;1663;608;#header;723;66;1663;608
Source Sent:
clicks=.testimonial%3B1119%3B316%3B1663%3B608%3B%23header%3B723%3B66%3B1663%3B608
PHP Page
<?php
$clicks = $_GET["clicks"];
$clickArray = explode(";",$clicks);
$arrays = array_chunk($clickArray, 5);
foreach ($arrays as $array_num => $array) {
foreach ($array as $item_num => $item) {
echo "". $item . "<br/>";
}
}
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "clickmap";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO data (user_id, identifier_name, pos_x, pos_y, window_width, window_height, status)
VALUES ('1', '$postIdentifier', '$postPos_x', '$postPos_y','$postWindowWidth','$postWindowHeight', 'ok')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Current PHP Result:
.testimonial
1119
316
1663
608
#header
723
66
1663
608
New record created successfully
This should work, but using extract is usually not recommended as it can easily lead to bugs that are hard to debug.
$keys = array('postIdentifier', 'postPos_x', 'postPos_y','postWindowWidth','postWindowHeight');
foreach ($arrays as $array_num => $array) {
$values = array();
foreach ($array as $item_num => $item) {
$values[] = $item;
}
$data = array_combine($keys, $values);
extract($data); // now your variables are declared with the right values http://php.net/manual/en/function.extract.php
// .. run SQL insert here
}

:Store SQL Data in a php array

I need to add data from mySQL to an array in a php script. However, the script is set to execute once a day automatically, and the array would vary in size. Is there a way to make a php array that varies in size depending on the amount a data acquired from mySQL?
Update:
So far this is what I have (after removing all the confidential info, of course)
$var1 = array();
$var2 = array();
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully";
}
echo "\r\n";
//select data from
$sql = //SQL File here
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc()) {
$var1 = $row[Row 1];
$var2 = $row[Row 2];
}
?>
Depending on how you grab your info, you can add each line from the MySQL query to an array as you loop through results.
while( $row = mysql_fetch_assoc( $result)){
$new_array[] = $row;
}

Categories