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
}
Related
Forgive me if the question is a little odd
I can clarify if needed:
I have the code that can connect to a mysql database as normal, however i have encapsulated it as a class:
<?php
define("HOST", "127.0.0.1"); // The host you want to connect to.
define("USER", "phpuser"); // The database username.
define("PASSWORD", "Secretpassword"); // The database password.
class DBConnection{
function conn($sql, $database){
$DB = new mysqli(HOST,USER,PASSWORD,$database);
if ($DB->connect_error){
die("Connection failed: " . $DB->connect_error);
exit();
}
if ($result = $DB->query($sql)){
return TRUE;
$DB->close();
}
else{
echo "Error: " . $sql . "<br>" . $DB->error;
$DB->close();
}
}
}
?>
I have done it this way so i can include this class in any subsequent php page and allow them to send it an sql statment and the database, see below as an example:
$sql = ("INSERT INTO users (first_name, last_name, username, email, password, group_level) VALUES ('John', 'Doah','JDoah', 'example#email', 'password', 'user')");
$DB = new DBConnection;
$result = $DB->conn($sql,"members");
if ($result ==TRUE){
return "Record added sucessfully";
}
This works fine.
however, im looking to send other sql statments to DBConnection.
How do i do that and to have it pass back any results that it recives? errors, boolean, row data etc. The caller will worry about parsing it.
Hopefully that makes sense.
This is an old class I used to use way back in the days of mysql still works but will need to be updated for mysqli or newer
class DBManager{
private $credentials = array(
"host" => "localhost",
"user" => "",
"pass" => "",
"db" => ""
);
function DBManager(){
$this->ConnectToDBServer();
}
function ConnectToDBServer(){
mysql_connect($this->credentials["host"],$this->credentials["user"],$this->credentials["pass"]) or die(mysql_error());
$this->ConnectToDB();
session_start();
}
function ConnectToDB(){
mysql_select_db($this->credentials["db"]) or die(mysql_error());
}
function Insert($tableName,$data){
$parameters = '';
$len = count($data);
$i = 0;
foreach($data as $key => $value){
if(++$i === $len){
$parameters .= $key . "='$value'";
}else{
$parameters .= $key . "='$value'" . ", ";
}
}
$query = "INSERT INTO $tableName SET $parameters";
mysql_query($query) or die(mysql_error());
return true;
}
function GetRow($tableName,$select,$where){
$selection = '';
$len = count($select);
$i = 0;
foreach($select as $key){
if(++$i === $len){
$selection .= $key;
}else{
$selection .= $key . ",";
}
}
$whereAt = '';
foreach($where as $key => $value){
$whereAt .= $key . "='$value'";
}
$query = "SELECT $selection FROM $tableName WHERE $whereAt";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
return $row;
}
}
}
The key things here is you can create a persistent connection to your database without rewriting a bunch of code
Example
global $DB;
$DB = new DBManager();
Since the connection happens in the constructor you will now have a connection on the page you call this code and can begin getting and setting to the database through use of $DB->GetRow() and $DB->Insert() which makes things much easier and was modeled after the $wpdb instance which is a class that manages the database in wordpress sites
Examples
For these examples we will assume you have a table as such
Insert new student
//create an associative array
$data = array(
"student_id" => 1,
"birth_date" => "02/06/1992",
"grade_level" => 4
);
//Send Call
$dm->Insert("student",$data);
Get data
//Create selection
$selection = array("grade_level");
//Create associative array for where we want to find the data at
$where = array(
"id" => 1
);
//Get Result
$result = $dm->GetRow("student",$selection,$where);
//do something with result
echo $result->grade_level;
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();
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
I'm trying to import data from a JSON feed using PHP into a MySQL database.
I have the code below but am not getting anywhere with it.
I keep just getting Connected to Database but nothing is being pulled in from the JSON data.
The JSON data is being created from a feed using import.io.
Any help appreciated
JSON data here
<?php
$data = file_get_contents('https://query.import.io/store/connector/e18543ae-48d1-47d3-9dc7-c3d55cab2951/_query?_user=363ec2db-fb95-413f-9a20-3fe89acbf061&_apikey=HOXvwSMX4HlmqH123i5HeELV6BwKq%2BFRInTzXc4nfl5VtP0pJyChxMT9AEiu1Ozi0vWZmUB%2BKcSsxHz2ElHNAg%3D%3D&format=JSON&input/webpage/url=http%3A%2F%2Fsports.yahoo.com%2Fgolf%2Fpga%2Fleaderboard');
$array = json_decode($data, true);
$rows = array();
$index = 0;
foreach($array['results'] as $mydata)
{
print_r($mydata);
echo "<br>";
foreach($mydata as $key => $value)
{
print_r ($key);
print_r ($value);
echo $index;
echo "<br><br>";
$rows[] = "('" . $value . "')";
}
echo "<br>";
$index++;
}
echo "<br><br><br>";
print_r ($rows);
$values = implode(",", $rows);
echo "<br><br><br>";
print_r ($values);
$hostname = 'localhost'; // write the rest of your query
$username = 'username';
$password = 'password';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
echo 'Connected to database<br />'; // echo a message saying we have connected
$count = $dbh->exec("INSERT INTO import_io (total, round_1, round_2, round_3, round_4, thru, name/_source, name, today, name/_text, strokes) VALUES ($values)");
echo $count;// echo the number of affected rows
$dbh = null;// close the database connection
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
First of here we have to fetch every row and then do another loop to fetch every value contained in that row, in this way we will obtain a 2D Array containing the data to format to put after in the db.
$i = 0;
foreach($array['results'] as $result){
foreach ($result as $key => $value)
$rows[$i][] = "'" . $value . "'";
$i++;
}
Then, here we format the data in order to fit our query that will be executed for every row fetched before.
try{
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
foreach ($rows as $row) {
$row = implode(",",$row); //making a string from an array with each item separated by comma
$query = "INSERT INTO import_io (total, round_1, round_2, round_3, round_4, thru, name/_source, name, today, name/_text, strokes) VALUES ($row)<br>";
$count = $dbh->exec($query);
}
$dbh = null;// close the database connection
}catch(PDOException $e){
echo $e->getMessage();
}
This is a follow up question , earlier i had asked
about inserting json into mysql . I encoded it again and now i want it to be printed back to mysql . I don't know how am i supposed to print the encoded json output as string back into mysql . Folowing is my current code
<?php
$json = array
(
array("pineapple","yellow"),
array("watermelon","red"),
array("orange","orange")
);
var_dump($json);
var_dump(json_decode($json, true));
$newelements = json_encode( $json, JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE );
echo $newelements;
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("json",$dbhandle)
or die("Could not select json");
// foreach ($enc as $fruit => $color) {
$db_insert = mysql_query("INSERT INTO fruits (fruit,color) VALUES('$fruit','$color')");
mysql_query($db_insert);
if (!$db_insert)
{
die('Could not connect - event insert failed: ' . mysql_error());
}
// }
?>
Any help would be much appreciated .Thanks in advance :)
Because you have an array of arrays, the correct foreach would look like this:
$values = array();
foreach ($newelement as $element) {
$values[] = "('".mysql_real_escape_string($element[0])."','".mysql_real_escape_string($element[1])."')";
}
$db_insert = mysql_query("INSERT INTO fruits (fruit,color) VALUES ".implode(",", $values);