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
Related
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','|', ',' )
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
I have an array
Array
(
[0] => Array
(
[NT_NOTAFINAL] => 10.00
[M_DESCRICAO] => ARTE
[PE_DESCRICAO] => 1 BIMESTRE
)
[1] => Array
(
[NT_NOTAFINAL] => 10.00
[M_DESCRICAO] => ARTE
[PE_DESCRICAO] => 2 BIMESTRE
)
[2] => Array
(
[NT_NOTAFINAL] => 10.00
[M_DESCRICAO] => ARTE
[PE_DESCRICAO] =>3 BIMESTRE
)
)
Now I'm trying create an associative array to return JSON something like this:
"Materia":[{"descricao":"ARTE", "Notas":["1 BIMESTRE":10.00, "2 BIMESTRE":10.00, "3 BIMESTRE":10.00]}]
I don't know how I could create this associative array to this JSON result from this array that I'm posting.
I'm trying create like this but the result what I need does not return
$notas = '';
$materia = '';
foreach($lista as $value){
if($value["M_DESCRICAO"] != $materia){
$materia = $value["M_DESCRICAO"];
}
$notas = array("Descricao"=>$materia, "Notas"=>array($value["PE_DESCRICAO"]=>$value["NT_NOTAFINAL"]));
}
$result = array("Materia"=>array($notas));
echo json_encode($result);
The result to what I'm trying is
{
"Materia": [
{
"Descricao": "ARTE",
"Notas": {
"3 BIMESTRE": "10.00"
}
}
]
}
How could I create this associative array to return this JSON like I need ?
Edit
$notas = array();
$materia = '';
$materia_array = array();
foreach($lista as $value){
if($materia == ''){
$materia = $value["M_DESCRICAO"];
}
if($value["M_DESCRICAO"] != $materia){
array_push($materia_array, (array("Descricao"=>$materia,"Notas"=>$notas)));
$notas = array();
$materia = $value["M_DESCRICAO"];
}else{
array_push($notas, array($value["PE_DESCRICAO"]=>$value["NT_NOTAFINAL"]));
}
}
$result = array("Materia"=>$materia_array);
echo json_encode($result);
Result
{
"Materia": [
{
"Descricao": "ARTE",
"Notas": [
{
"1 BIMESTRE": "10.00"
},
{
"2 BIMESTRE": "10.00"
},
{
"3 BIMESTRE": "10.00"
}
]
},
{
"Descricao": "C.SOCIAIS",
"Notas": [
{
"2 BIMESTRE": "10.00"
},
{
"3 BIMESTRE": "9.50"
}
]
},
{
"Descricao": "CIĆNCIAS E P. S.",
"Notas": [
{
"2 BIMESTRE": "9.50"
},
{
"3 BIMESTRE": "10.00"
}
]
}
]
}
I've refactored your last edit to remove some code duplication and complexity.
$result = array();
foreach ($lista as $value) {
$materia = $value['M_DESCRICAO'];
if (!isset($result[$materia])) {
$result[$materia] = array(
'Descricao' => $materia,
'Notas' => array()
);
}
$result[$materia]['Notas'][] = array(
$value['PE_DESCRICAO'] => $value['NT_NOTAFINAL']
);
}
$result = array('Materia' => array_values($result));
echo json_encode($result);
In addition to my comment, this would be the code to push all notes to an array as long as the M_DESCRICAO does not change, so the starting array $lista needs to be ordered first. Is this what you were after (code is not tested, office computer :-))?
$notas = $materia = null;
$result = $tmp = array();
$len = count($lista);
for ($i=0;$i<$len;$i++) {
$notas = array();
$materia = $lista[$i]["M_DESCRICAO"];
while (($materia == $lista[$i+1]["M_DESCRICAO"]) && ($i < ($len -1))) {
$notas[$lista[$i]["PE_DESCRICAO"]] = $lista[$i]["NT_NOTAFINAL"];
$i++;
}
// now $notas holds all corresponding entries
$tmp[] = array("Descricao"=>$materia, "Notas" => $notas);
}
$result = array("Materia"=>array($tmp));
echo json_encode($result);
I worked out an untested (there might be some errors, but logically it should work) piece of code, but it might help you:
$notas;
$materia = '';
$materia_array;
foreach($lista as $value){
if($materia == '')
$materia = $value["M_DESCRICAO"];
if($value["M_DESCRICAO"] != $materia){
array_push($materia_array, (array("Descricao"=>$materia,"Notas"=>$notas));
unset($notas); //<--------
$notas = array();//<--------
$materia = $value["M_DESCRICAO"];
}
else
{
array_push($notas, array($value["PE_DESCRICAO"]=>$value["NT_NOTAFINAL"]))
}
}
$result = array("Materia"=>$materia_array);
echo json_encode($result);
This should work for multiple M_DESCRICAO values