I want import an input List in csv format, with separator (|), from an Textarea to my MySQL Database.
But it always failed, also if its in the correct format.
It comes the message: Error, 0 added successfully.
My format:
Thomas|Maier|5778011152|Bahnweg|232
Any one an Idea?
if(isset($_POST["base_name"]) && isset($_POST["new_entry"])) {
$myList = preg_replace("/\r|\n/", "", preg_split("/$\R?^/m", $_POST["new_entry"]));
foreach($myList as $info) $csv[] = explode($_POST["separator"], $info);
$csvParams = $csv[0];
array_shift($csv);
$success = 0;
$total = 0;
foreach($csv as $info) {
$sqlInsert = array_combine($csvParams, $info);
$sqlInsert["base"] = $_POST["base_name"];
$sqlInsert["info"] = "unbenutzt";
$p = softwareInsertArray($softwareSqlLink, $sqlInsert, "person");
if($p) $success++;
$total++;
}
$q = softwareRunQuery($softwareSqlLink, false, "INSERT INTO statistics (`key`, `val`) VALUES ('".$_POST["base_name"]."|profit', '0');");
}
if(isset($total)) {
if($total == $success && $total > 0 && $q) {
$alert = array("type" => "success", "header" => "Erfolgreich!", "text" => "Success.");
softwareSqlLog($softwareSqlLink, "person", array("status" => 1, "info" => array("base" => $_POST["base_name"], "text" => $success." person added successfully")));
} else {
$alert = array("type" => "danger", "header" => "Fehler!", "text" => $success."/".$total." sucess.");
softwareSqlLog($softwareSqlLink, "person", array("status" => 0, "info" => array("base" => $_POST["base_name"], "text" => $success."/".$total." added.")));
}
}
softwareInsertArray code: pastebin.com/raw/vUnQTpxU
Do you just want to replace the pipes with commas?
IE SELECT replace('Thomas|Maier|5778011152|Bahnweg|232','|', ',' )
Related
I am not getting any output from the bottom half as I was expecting. I can grab the top table's data, but I am also trying to grab the bottom table data and place encode them into json. The columns I need to grab are
1. Week Date Home Away At Notes
<?php
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML(file_get_contents('https://www.leagueleader.net/sharedreport.php?operatorid=98&code=bc155b01-7492-412d-aa75-3c1e357248f1'));
$doc->strictErrorChecking = false;
$pre = [];
$keys = ['team', 'div', 'team-site-name', 'site-address', 'site-phone'];
$keys2 = ['week', 'date', 'home', 'away', 'at', 'notes'];
foreach ($doc->getElementsByTagName('table') as $k => $table) {
if (strpos($table->getAttribute('class'), 'report') === false) {
continue;
}
foreach ($table->getElementsByTagName('tr') as $i => $tr) {
if ($tr->parentNode->nodeName === 'thead') continue; // skip headers
$row_values = [];
foreach ($tr->childNodes as $td) {
$text = trim($td->nodeValue);
if ($text === '') continue;
$row_values[] = $text;
}
if($k == 1 ){
$row_values = array_combine($keys, $row_values);
}else if($k == 2 ){
unset($row_values[1]);
$row_values = array_combine($keys2, $row_values);
}
$pre[$row_values['name']][] = $row_values;
}
}
$combined = [];
foreach($pre as $week => $row){
$combined[$name] = [
"week"=> $week,
"team"=> $row[0]['team'],
"div"=> $row[0]['div'],
"team-site-name" => $row[0]['team-site-name'],
"site-address" => $row[0]['site-address'],
"site-phone" => $row[0]['site-phone'],
//"week" => $row[1]['week'],
"date" => $row[1]['date'],
"home" => $row[1]['home'],
"away" => $row[1]['away'],
"at" => $row[1]['at'],
"notes" => $row[1]['notes']
];
}
echo '<pre>'.json_encode($combined, JSON_PRETTY_PRINT).'</pre>';
?>
Here is the output
{
"": {
"week": "",
"team": "1",
"div": "A",
"team-site-name": "Team 01Freer Bar",
"site-address": "\u00a07355 Michigan Ave Detroit, MI 48210",
"site-phone": "\u00a03138993699",
"date": null,
"home": null,
"away": null,
"at": null,
"notes": null
}
}
To get the data from the second table with the matches, I've changed the processing to use XPath. This extracts the <tr> tags from the body of the second table with class='report' (using //table[#class='report'][2]/tbody/tr).
So this will return all of the rows in the body of the table. Then extract all of the <td> elements and pick out the details in the row. If there is a week/date present it just overwrites the current data, if there are match details it creates a row on the output...
$xpath = new DOMXPath($doc);
$reportRow = $xpath->query("//table[#class='report'][2]/tbody/tr");
$matches = [];
$week = '';
$date = '';
foreach ($reportRow as $row) {
$cells = $row->getElementsByTagName("td");
// Set week and date if present in the current row
$week = trim($cells[0]->textContent)?:$week;
$date = trim($cells[1]->textContent)?:$date;
// Extract the other details
$teamHome = trim($cells[2]->textContent);
$teamAway = trim($cells[3]->textContent);
$at = trim($cells[4]->textContent);
$notes = trim($cells[5]->textContent);
// If there are some match details, the store them
if ( !empty($teamHome) ) {
$matches[] = ["week" => $week, "date" => $date,
"teamHome" =>$teamHome, "teamAway" =>$teamAway,
"at" => $at, "notes" => $notes
];
}
}
print_r($matches);
This gives...
Array
(
[0] => Array
(
[week] => 1
[date] => 09/10/2019
[teamHome] => Team 01
[teamAway] => BYE
[at] => BYE
[notes] =>
)
I want import an List in csv format, with seperator, from an Textarea to my MySQL Database.
But it always failed, also if its in the correct format.
Input Text:
Thomas|Maier|5778011152|Bahnweg|232
PHP Code:
<?php
if(isset($_POST["base_name"]) && isset($_POST["new_entry"])) {
$myList = preg_replace("/\r|\n/", "", preg_split("/$\R?^/m", $_POST["new_entry"]));
foreach($myList as $info) $csv[] = explode($_POST["separator"], $info);
$csvParams = $csv[0];
array_shift($csv);
$success = 0;
$total = 0;
foreach($csv as $info) {
$sqlInsert = array_combine($csvParams, $info);
$sqlInsert["base"] = $_POST["base_name"];
$sqlInsert["info"] = "unbenutzt";
$p = softwareInsertArray($softwareSqlLink, $sqlInsert, "person");
if($p) $success++;
$total++;
}
$q = softwareRunQuery($softwareSqlLink, false, "INSERT INTO statistics (`key`, `val`) VALUES ('".$_POST["base_name"]."|profit', '0');");
}
if(isset($total)) {
if($total == $success && $total > 0 && $q) {
$alert = array("type" => "success", "header" => "Erfolgreich!", "text" => "Success.");
softwareSqlLog($softwareSqlLink, "person", array("status" => 1, "info" => array("base" => $_POST["base_name"], "text" => $success." person added successfully")));
} else {
$alert = array("type" => "danger", "header" => "Fehler!", "text" => $success."/".$total." sucess.");
softwareSqlLog($softwareSqlLink, "person", array("status" => 0, "info" => array("base" => $_POST["base_name"], "text" => $success."/".$total." added.")));
}
}
?>
If comes always 0 added = Nothing Uploaded. Anyone an Idea?
Thanks
I'm trying to export my database in excel using php. but the while loop is only inserting one row of values in the array and exported excel file will only have one only row of data.
I'm using a nested loop for table callback to insert it's data if it's not empty that is. So, basically there is two databases of values being exported to one excel file. First the data is is being stored in an array and then it is exported as an excel file.
Here's the code :
$sql = "SELECT * FROM leads";
$result = mysqli_query($conn, $sql);
$data = array();
while ($row1 = mysqli_fetch_array($result))
{
if ($row1["status"] == "1")
{
$status = "New";
}
if ($row1["status"] == "2")
{
$status = "Assigned";
}
if ($row1["status"] == "3")
{
$status = "Pending";
}
if ($row1["status"] == "4")
{
$status = "Closed";
}
if ($row1["status"] == "5")
{
$status = "Denied";
}
$id = $row1["id"];
$sql2 = "SELECT * FROM callback WHERE lead_id=$id ORDER BY id DESC LIMIT 1";
$result2 = mysqli_query($conn, $sql2);
if ($result2)
{
while ($row2 = mysqli_fetch_array($result2))
{
$data[] = array(
"Created" => $row1["curdate"],
"Customer Name" => $row1["cname"],
"Designation" => $row1["designation"],
"Contact" => $row1["number"],
"Company" => $row1["company"],
"Address" => $row1["street"],
"Landmark" => $row1["landmark"],
"Zip" => $row1["zip"],
"Products" => $row1["product"],
"Last Callback" => $row2["callback"],
"Last Visit" => $row2["vdate"],
"Status" => $status
);
}
}
else
{
$data[] = array(
"Created" => $row1["curdate"],
"Customer Name" => $row1["cname"],
"Designation" => $row1["designation"],
"Contact" => $row1["number"],
"Company" => $row1["company"],
"Address" => $row1["street"],
"Landmark" => $row1["landmark"],
"Zip" => $row1["zip"],
"Products" => $row1["product"],
"Last Callback" => "NULL",
"Last Visit" => "NULL",
"Status" => $status
);
}
}
What am i doing wrong? Also i'm a noob at this so, please go easy on me thanks.
$result2 is a mysqli_result object, you can't use it in an if statement. You should use its num_rows property instead i.e.
if ($result2->num_rows > 0)
(in place of if ($result2))
I have json input as mentioned below am decoding the the json response and inserting it into the mysql database,Now am converting this into Codeigniter I am not able to understand how to write the controller and the model for the below code,Please let me know how to write the controller and model, also am providing the controller and model which is written by me
PHP Code
<?php
include ('config.php');
// read json file
date_default_timezone_set('Asia/Kolkata');
$timestamp = time();
$date_time = date("Y-m-d H:i:s", $timestamp);
$createdon = $date_time;
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// $filename = 'employee.json';
// $json_data = file_get_contents($filename);
$json_data = $_POST['QUESTION'];
//convert json object to php associative array
$data = json_decode($json_data, true);
// print_r($data);
if (is_array($data) || is_object($data)) {
$jsonData = $data['DATA'];
$jsonAnswers = $data['ANSWERS'];
$drcode = $data['DATA']['DRCODE'];
$divcode = $data['DATA']['DIVCODE'];
$brdcode = $data['DATA']['BRDCODE'];
$prdcode = $data['DATA']['PRDCODE'];
// echo $drmobile." -- ";
for ($i = 0;$i < sizeof($data['ANSWERS']);$i++) {
$quecode[$i] = $data['ANSWERS'][$i]['ADCODE'];
$answer[$i] = $data['ANSWERS'][$i]['ANSWER'];
$quecodes = $quecode[$i];
$answers = $answer[$i];
// echo $quecode[$i]." <--> ".$answer[$i]."<br/>";
$sql = "INSERT INTO ANSWERS(DRCODE,ADCODE,DIVCODE,BRDCODE,PRDCODE,ANSWERS,CREATEDON)VALUES ('$drcode', '$quecode[$i]', '$divcode', '$brdcode', '$prdcode', '$answer[$i]', '$createdon')";
$qur = mysql_query($sql);
if ($qur) {
$json = array("status" => 1, "msg" => "Data added Successfully!");
} else {
$json = array("status" => 2, "msg" => "Already Submitted");
}
}
// echo "<br/>-----------<br/>";
}
} else {
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
//close connection
?>
Json Input
{
"DATA": {
"DRCODE": "D40504",
"DIVCODE": 1,
"BRDCODE": 5,
"PRDCODE": 5
},
"ANSWERS": [{
"ADCODE": 1,
"ANSWER": "VERY GOOD"
}, {
"ADCODE": 2,
"ANSWER": "GOOD"
}, {
"ADCODE": 3,
"ANSWER": "SGH"
}, {
"ADCODE": 4,
"ANSWER": "NO"
}, {
"ADCODE": 5,
"ANSWER": "NO"
}, {
"ADCODE": 6,
"ANSWER": "CGHJ"
}]
}
Controller
public function feedback_post() {
$json_data = $this->post('QUESTION');
$data = $this->json_decode($json_data, true);
if (is_array($data) || is_object($data)) {
$jsonData = $this->$data['DATA'];
$jsonAnswers = $this->$data['ANSWERS'];
$drcode = $this->$data['DATA']['DRCODE'];
$divcode = $this->$data['DATA']['DIVCODE'];
$brdcode = $this->$data['DATA']['BRDCODE'];
$prdcode = $this->$data['DATA']['PRDCODE'];
for ($i = 0;$i < sizeof($data['ANSWERS']);$i++) {
$quecode[$i] = $this->$data['ANSWERS'][$i]['ADCODE'];
$answer[$i] = $this->$data['ANSWERS'][$i]['ANSWER'];
$quecodes = $this->$quecode[$i];
$answers = $this->$answer[$i];
}
$insert_array = array('DRCODE' => $drcode, 'DIVCODE' => $divcode, 'BRDCODE' => $speciality, 'PRDCODE' => $prdcode, 'ANSWER' => $answers, 'ADCODE' => $quecodes);
$feedback_data = $this->Rest_user_model->feedbacksubmission($insert_array);
if ($feedback_data) {
$message = ['status' => 1,
// 'result' => array(),
'message' => 'Feedback Submitted Successfully'];
} else {
$message = ['status' => 2,
// 'result' => array(),
'message' => 'Feedback Submitted Successfully'];
}
$this->set_response($message, REST_Controller::HTTP_OK);
}
}
try this
public function feedback_post()
{
$objDate = new DateTime();
$data = json_decode($this->input->post('QUESTION'), true);
if (is_array($data))
{
foreach($data['ANSWERS'] AS $arrAnswer)
{
$arrInsertData =
[
'DRCODE' => $data['DATA']['DRCODE'],
'DIVCODE' => $data['DATA']['DIVCODE'],
'BRDCODE' => $data['DATA']['BRDCODE'],
'PRDCODE' => $data['DATA']['PRDCODE'],
'ADCODE' => $arrAnswer['ADCODE'],
'ANSWERS' => $arrAnswer['ANSWER'],
'CREATEDON' => $objDate->format('Y-m-d H:i:s'),
];
$feedback_data = $this->Rest_user_model->feedbacksubmission($arrInsertData);
$message = ($feedback_data) ? ['status' => 1, 'message' => 'Feedback Submitted Successfully'] : ['status' => 2, 'message' => 'Already Submitted'];
}
}
else
{
$message = ["status" => 0, "msg" => "Request method not accepted"];
}
$this->set_response($message, REST_Controller::HTTP_OK);
}
this is pretty much basic understanding of php - but you've to ask yourself - if you've multiple answers - what happens if one fails and one is successful ?
Because your sample php code is simply wrong...
Am having this problem that I have never experienced before. php array_push does not work in while loop. When I use while loop nothing is printed on the browser but when I fetch data without while loop, it's working fine. Where could I be going wrong. I have struggled it seems not to work.
This is my php code:
function getFeaturedCrops(){
require "config.inc.php";
try{
$query = $conn->prepare("SELECT * FROM crops WHERE category = ? ");
$query->bindValue(1, 1);
$query->execute();
if($query->rowCount()){
//echo "nice";
$jsonArray = array();
while($data = $query->fetch(PDO::FETCH_ASSOC)){
// here we are loading either animals ar crops
$type = $data['type'];
$name = $data['name'];
$description = $data['description'];
$image = $data['image'];
$id = $data['salt'];
if(strlen($description) > 50){
$shortDescription = substr($description, 0, 50)."...";
} else {
$shortDescription = $description;
}
if(strlen($name) > 20){
$shortName = substr($name, 0, 20)."...";
} else {
$shortName = $name;
}
if(strlen($type) > 20){
$shortType = substr($type, 0, 20)."...";
} else {
$shortType = $type;
}
//echo "$shortDescription\n";
array_push($jsonArray,
array(
"type" => $type,
"shortType" => $shortType,
"name" => $name,
"shortName" => $shortName,
"description" => $description,
"shortDescription" => $shortDescription,
"image" => $image,
"id" => $id,
"success" => true
)
);
}
} else {
array_push($jsonArray, array(
"type" => "default",
"shortType" => "default",
"name" => "default",
"shortName" => "default",
"description" => "default",
"shortDescription" => "default",
"image" => "default",
"id" => "default",
"success" => false
)
);
}
//echo "well data";
echo json_encode(array("Items" => $jsonArray));
} catch(Exception $e){
die($e->getMessage());
}
}
Then this how am calling my function:
getFeaturedCrops();
This is my database screenshot