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))
Related
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 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','|', ',' )
What I'm trying to do:
Pull data from a database and insert it into an array
The code I'm using:
sql = "SELECT * FROM `products`, categories WHERE category = cat_ID AND pro_ID = " . $_GET['id'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$name = $row['pro_name'];
$cartContents[$name] = array(
"id" => $row['pro_ID'],
"name" => $row['pro_name'],
"price" => $row['price'],
"quantity" => $_GET['q']
);
}
The problem:
This does indeed take the values from the database and insert them into the array, but it replaces everything dat was in the array before this.
What I've tried:
- Replacing array(...) with [...]
- Using the following code:
$cartContents[$name]["id"] = $row['pro_ID'];
$cartContents[$name]["name"] = $row['pro_name'];
$cartContents[$name]["price"] = $row['price'];
$cartContents[$name]["quantity"] = $_GET['q'];
Any help would be greatly appreciated, thank you!
If you don't want the data to be replaced for the $cartContents[$name] just update your code like this;
$cartContents[$name][] = array(
"id" => $row['pro_ID'],
"name" => $row['pro_name'],
"price" => $row['price'],
"quantity" => $_GET['q']
);
Hi I have an error when I call a function.
"Warning: Illegal string offset 'id' in C:\xampp\htdocs\blog\posts.php
on line 28
2"
function:
function get_short_posts() {
$sql = "SELECT * FROM posts ORDER by id DESC LIMIT 0, 5";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$timestamp = new DateTime($row['date']);
return array (
"id" => $row['id'],
"title" => $row['title'],
"content" => $row['content'],
"author" => $row['author'],
"date" => $timestamp->format('d-m-Y'),
"time" => $timestamp->format('H:i')
);
}
Call:
require_once "functions.php";
$_posts = get_short_posts();
foreach($_posts as $_post) {
echo $_post['id'];
}
You know you return after the first iteration in the get_short_posts function right, so the foreach will not work as expected.
Try:
<?php
function get_short_posts() {
$sql = "SELECT * FROM posts ORDER by id DESC LIMIT 0, 5";
$result = mysql_query($sql);
$return = array();
while($row = mysql_fetch_assoc($result)) {
$timestamp = new DateTime($row['date']);
$return[] = array (
"id" => $row['id'],
"title" => $row['title'],
"content" => $row['content'],
"author" => $row['author'],
"date" => $timestamp->format('d-m-Y'),
"time" => $timestamp->format('H:i')
);
}
return $return;
}
?>
<?php
require_once "functions.php";
foreach(get_short_posts() as $_post) {
echo $_post['id'];
}
?>
Also, Don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
function get_short_posts() {
$sql = "SELECT * FROM posts ORDER by id DESC LIMIT 0, 5";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$timestamp = new DateTime($row['date']);
$data [] = array (
"id" => $row['id'],
"title" => $row['title'],
"content" => $row['content'],
"author" => $row['author'],
"date" => $timestamp->format('d-m-Y'),
"time" => $timestamp->format('H:i')
);
}
return $data;
}
you return data, so the loop stops, save your data in a array and return that array like abive code
Your code is wrong it should be as below, assuming the query is returning data as mentioned.
function get_short_posts() {
$sql = "SELECT * FROM posts ORDER by id DESC LIMIT 0, 5";
$result = mysql_query($sql);
$rows = array();
$return_data = array();
while($row = mysql_fetch_assoc($result)) {
$timestamp = new DateTime($row['date']);
$data = array (
"id" => $row['id'],
"title" => $row['title'],
"content" => $row['content'],
"author" => $row['author'],
"date" => $timestamp->format('d-m-Y'),
"time" => $timestamp->format('H:i')
);
$return_data[] = $data;
}
return $return_data ;
}
require_once "functions.php";
$posts = get_short_posts();
foreach($posts as $key=>$val) {
echo $val['id'];
}
I have two tables that I want to convert them to json like this:
[
{
"date":"2013-07-20",
"id":"123456",
"year":"2013",
"people":[
{
"name":"First",
"age":"60",
"city":"1"
},
{
"name":"second",
"age":"40",
"city":"2"
},
{
"name":"third",
"age":"36",
"city":"1"
}
]
}
]
but the result of my code is this:
[
{
"date":"2013-07-20",
"id":"123456",
"year":"2013",}
,{
"people":[
{
"name":"First",
"age":"60",
"city":"1"
},
{
"name":"second",
"age":"40",
"city":"2"
},
{
"name":"third",
"age":"36",
"city":"1"
}
]
}
]
the code creates a new object to the array "people" and I want that are in the same object
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
$json2['people'] = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json2['people'],$row_temp);
}
array_push($json, $json2);
echo Json_encode($json);
How I can make the array is in the same object as the table "data"?
Many thanks
I think you may try this
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
// I think, you'll get a single row, so no need to loop
$json = mysql_fetch_array($result, MYSQL_ASSOC);
$json2 = array();
while ($row = mysql_fetch_assoc($fetch)){
$json2[] = array(
'name' => $row["name"],
'age' => $row["age"],
'city' => $row["city"]
);
}
$json['people'] = $json2;
echo json_encode($json);
Result of print_r($json) should be something like this
Array
(
[date] => 2013-07-20
[year] => 2013
[id] => 123456
[people] => Array
(
[0] => Array
(
[name] => First
[age] => 60
[city] => 1
)
[1] => Array
(
[name] => second
[age] => 40
[city] => 2
)
)
)
Result of echo json_encode($json) should be
{
"date" : "2013-07-20",
"year":"2013",
"id":"123456",
"people":
[
{
"name" : "First",
"age" : "60",
"city" : "1"
},
{
"name" : "second",
"age" : "40",
"city" : "2"
}
]
}
If you do echo json_encode(array($json)) then you will get your whole json wrapped in an array, something like this
[
{
"date" : "2013-07-20",
"year":"2013",
"id":"123456",
"people":
[
{
"name" : "First",
"age" : "60",
"city" : "1"
},
{
"name" : "second",
"age" : "40",
"city" : "2"
}
]
}
]
You were very close, but you want the People array to be a direct value of the outer array and you've wrapped it in an extra array.
Also, please note that the MySQL library you are using is deprecated. That means it will be removed from PHP in a future release. You should replace calls from the MySQL_* family of functions with either mysqli or pdo
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
$json['people'] = array();
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json['people'],$row_temp);
}
echo Json_encode($json);
You can make it work by waiting to use the key people until the very end when you join the two arrays. Up until then, just load the data into $json and $json2.
$json = array('date' => '2013', 'id' => '123456', 'year' => '2013');
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
$json2 = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json2, $row_temp);
}
$json['people'] = $json2;
echo Json_encode($json);