<?php
echo "Connecting Database <br>";
$server = 'UKVDEMO03'; //Here you're server
$database = 'smtpFetch';//here the database you want to connect to
$user = 'shoaibsg';//here te user WHO HAS THE RIGHT PERMISSIONS AT THE DATABASE
$pass = '1111111';//and here the user's password
$dsn = "Driver={SQL Server};Server=$server;Database=$database;";
$connect = odbc_connect($dsn, $user, $pass);
echo "Successfully connected....";
//getting subscribe user detail
$subQuery="select emailAddress, dataSet from userDetail";
$subRes=odbc_exec($connect, $subQuery);
$ix=odbc_num_rows($subRes);
//$newArray[]=$newArray array;
$row[]=array();
$newArrayD[]=$row;
$i=0;
$xc=0;
if($ix>0)
{
while($row=odbc_fetch_array($subRes))
{
$newArrayD[$row['emailAddress']] =$row['emailAddress'];
$newArrayD[$row['dataSet']] =$row['dataSet'];
}
}
foreach($newArrayD as $arrayD)
{ $i++;
echo "<br> -" . $arrayD;
echo "-i increment -" . $i;
}
?>
The above displays the below output
-Array
-shoaib#xyz.com
-SSCRUS_CS2002
-nick#xyz.com
-SSCE_CS2002
Now the problem: if I need to display only the emailAddress only in foreach loop it only displays the first character (I used below in foreach loop)
echo "<br> -" . $arrayD['emailAddress'];
such as above output displays as
-
-s
-S
-n
-S
I am baffled, please please help
Your code to generate the array is off. Try this:
while ($row=odbc_fetch_array($subRes))
{
$newArrayD[$row['dataSet']] = $row['emailAddress'];
// This would generate for example $newArrayD['SSCRUS_CS2002'] = 'shoaib#xyz.com'
}
Then, to display them, iterate through the array:
foreach ($newArrayD as $dataset=>$emailaddress)
{
echo "- $emailaddress<br />";
}
EDIT - To save both in seperate arrays:
$newArrayD = array('dataset' => array(), 'emails' => array());
while ($row=odbc_fetch_array($subRes))
{
$newArrayD['dataset'][] = $row['dataSet'];
$newArrayD['emails'][] = $row['emailAddress'];
}
To iterate through the emails:
foreach ($newArrayD['emails'] as $emailaddress)
{
// Code you wish to execute
}
To iterate through the datasets:
foreach ($newArrayD['dataset'] as $dataset)
{
// Code you wish to execute
}
Using this method, the $newArrayD['dataset'][0] will be the dataset linked to $newArrayD['emails'][0] etc.
Related
I have a code below
<?php
/* Error display */
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '512M');
/* Requires */
require 'conn.php';
/* Parameters (DIM) */
$param_customer = $_POST['param_customer'];
$param_user = $_POST['param_user'];
/* Others */
$param_email = $_POST['email'];
$file_dump_area = "../general_sync/";
/* Array */
$jsonData = array();
$arr_result = array();
/******************************** Download customer *********************************/
$cur_filename = $file_dump_area . removeCharEmail($param_email) . "_" . $param_customer . ".csv";
$cur_file = fopen($cur_filename, "w");
$cur_sql = "CALL android_getCustomer('" .$param_email. "')";
$cur_result = mysqli_query($con,$cur_sql);
if ($cur_file && $cur_result) {
while ($row = $cur_result->fetch_array(MYSQLI_NUM)) {
fputcsv($cur_file, array_values($row));
}
array_push($arr_result, array('done_process' => "done_cus"));
}
fclose($cur_file);
/******************************** Download user *********************************/
$cur_filename = $file_dump_area . removeCharEmail($param_email) . "_" . $param_customer . "1.csv";
$cur_file = fopen($cur_filename, "w");
$cur_sql = "CALL android_getCustomer('" .$param_email. "')";
$cur_result = mysqli_query($con,$cur_sql);
if ($cur_file && $cur_result) {
while ($row = $cur_result->fetch_array(MYSQLI_NUM)) {
fputcsv($cur_file, array_values($row));
}
array_push($arr_result, array('done_process' => "done_user"));
}
fclose($cur_file);
$jsonData = array("received"=>$arr_result);
echo json_encode($jsonData,JSON_PRETTY_PRINT);
function removeCharEmail($val) {
$new_val1 = str_replace(".", "", $val);
$new_val2 = str_replace("#", "", $new_val1);
return $new_val2;
}
?>
The target output of that code is to create 2 csv which is it does but the problem is the 2nd csv has no data although the query shows some it does not write. I tried to copy the 1st line of codes. it does create the file but it didnt write
Whats the problem?
Updated with help of Mr. Barmar
i got this error Commands out of sync; you can't run this command now
The stored procedure is apparently returning two result sets. You need to fetch the next result set before you can start another query. Add:
$cur_result->close();
$con->next_result();
After each loop that fetches the results. See https://stackoverflow.com/a/14561639/1491895 for more details.
I have values in database like these :
Row 1 : ["2","3"]
Row 2 : ["1","3"]
Row 3 : ["2","3","4"]
In frontend i selected all rows, now i want to show count of similar values.
For eg : Desired o/p from above code : Count for 1 = 1 , 2 = 2 , 3 = 3 , 4 = 1
When i json_decode above values and using print_r i got like these :
Array ( [0] => 2 [1] => 3 )
Array ( [0] => 1 [1] => 3 )
Array ( [0] => 2 [1] => 3 [2] => 4 )
Note : List of rows can be increased, how can i find similar values.
I tried array_intersect as shown here , but didn't work.
Eg: image here
Please Note Data in image, is different from above data
Code to get above data :
$conn = new mysqli("localhost", "root", "", "ams");
$query="SELECT * FROM attendance WHERE subject = '$subj'";
$result = $conn->query($query);
<table class="table table-responsive">
<tr>
<th>Sr. No</th>
<th>Col 1 </th>
<th>Col 2</th>
</tr>
<form method="post">
<?php
$i=1;
if (mysqli_num_rows($result) > 0) {
while ($row=mysqli_fetch_assoc($result)) {
$data = $row['att'];
$data = json_decode($data);
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row['date1'] . "</td>";
echo "<td>" . print_r($data) . "</td>";
echo "</tr>";
$i++;
}
}
?>
</form>
</table>
So, I made this class for you. It will create the connection when you initalize it.
class RowData {
private $connection;
private $returnContent = array();
private $stmt = null;
function __construct() {
$connection = new PDO("mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DB, MYSQL_USERNAME, MYSQL_PASSWORD);
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection = $connection;
}
public function get($subj) {
$this->getContentFromDB($subj);
$this->parseContent();
return $this->returnContent;
}
private function getContentFromDB($subj) {
$stmt = $this->connection->prepare("SELECT * FROM attendance WHERE subject = '{$subj}'");
$stmt->execute();
$this->stmt = $stmt;
}
private function parseContent() {
$content = $stmt->fetchAll(PDO::FETCH_OBJ);
if(count($content) < 1) {
throw new Exception('Unable to find any attendies');
}
foreach($content as $values) {
$row = $this->getJsonArray($values->att);
$this->findValues($row);
}
}
private function getJsonArray($content) {
return json_decode($content);
}
private function findValues(array $row) {
foreach($row as $key => $value) {
if(isset($this->returnContent[$value])) {
$this->returnContent[$value] = $this->returnContent[$value] + 1;
} else {
$this->returnContent[$value] = 1;
}
}
return;
}
}
So, let me explain it. The constructor will be the function that is initialized when you write $x = new RowData();. It creates the connection the the MySQL database. All you have to do is change the MYSQL_HOST, MYSQL_DB, MYSQL_USERNAME, MYSQL_PASSWORD values to the appropriate ones. The only function that is available for you to use publicly would be the get() function. The get() function calls 2 separate functions and accepts one value as a parameter. The one value is what you called $subj. One of the functions in the get() function just gets the content from the MySql Table using the query you provided. The second function parseContent() gets an obj from PDO and loops through it. lastly, there is the findValues() function that accepts $row as a parameter. This function will see if the number is already in the data set. If it is, then it is basically a counter. Otherwise, it makes a new key and sets the value to 1.
The values returned from the get() function would be something like this:
array(2=>2, 1=>1, 3=>3, 4=>1)
To use this class, you would write something like this:
$rowData = new RowData();
try {
$content = $rowData->get();
} catch (Exception $e) {
// No results were found
}
Hope this helps! If you need help implementing this, let me know and i'll be more than happy to help you out!
I have a code that runs a query on an external (slow) API and loops through a lot of variables and inserts data, sends email, ect'.
This is the main function as an example:
// MAIN: Cron Job Function
public function kas_alert() {
// 0. Deletes all the saved data from the `data` table 1 month+ ago.
// $this->kas_model->clean_old_rows();
// 1. Get 'prod' table
$data['table'] = $this->kas_model->prod_table();
// 2. Go through each row -
foreach ( $data['table'] as $row ) {
// 2.2. Gets all vars from the first query.
$last_row_query = $this->kas_model->get_last_row_of_tag($row->tag_id);
$last_row = $last_row_query[0];
$l_aaa_id = $last_row->prod_aaa_id;
$l_and_id = $last_row->prod_bbb_id;
$l_r_aaa = $last_row->dat_data1_aaa;
$l_r_and = $last_row->dat_data1_bbb;
$l_t_aaa = $last_row->dat_data2_aaa;
$l_t_and = $last_row->dat_data2_bbb;
$tagword = $last_row->tag_word;
$tag_id = $last_row->tag_id;
$country = $last_row->kay_country;
$email = $last_row->u_email;
$prod_name = $last_row->prod_name;
// For the Weekly report:
$prod_id = $last_row->prod_id;
$today = date('Y-m-d');
// 2.3. Run the tagword query again for today on each one of the tags and insert to DB.
if ( ($l_aaa_id != 0) || ( !empty($l_aaa_id) ) ) {
$aaa_data_today = $this->get_data1_aaa_by_id_and_kw($l_aaa_id, $tagword, $country);
} else{
$aaa_data_today['data1'] = 0;
$aaa_data_today['data2'] = 0;
$aaa_data_today['data3'] = 0;
}
if ( ($l_and_id != 0) || ( !empty($l_and_id) ) ) {
$bbb_data_today = $this->get_data1_bbb_by_id_and_kw($l_and_id, $tagword, $country);
} else {
$bbb_data_today['data1'] = 0;
$bbb_data_today['data2'] = 0;
$bbb_data_today['data3'] = 0;
}
// 2.4. Insert the new variables to the "data" table.
if ($this->kas_model->insert_new_tag_to_db( $tag_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $aaa_data_today['data2'], $bbb_data_today['data2'], $aaa_data_today['data3'], $bbb_data_today['data3']) ){
}
// Kas Alert Outputs ($SEND is echoed in it's original function)
echo "<h1>prod Name: $prod_id</h1>";
echo "<h2>tag id: $tag_id</h2>";
var_dump($aaa_data_today);
echo "aaa old: ";
echo $l_r_aaa;
echo "<br> aaa new: ";
echo $aaa_data_today['data1'];
var_dump($bbb_data_today);
echo "<br> bbb old: ";
echo $l_r_and;
echo "<br> bbb new: ";
echo $bbb_data_today['data1'];
// 2.5. Check if there is a need to send something
$send = $this->check_if_send($l_aaa_id, $l_and_id, $l_r_aaa, $aaa_data_today['data1'], $l_r_and, $bbb_data_today['data1']);
// 2.6. If there is a trigger, send the email!
if ($send) {
$this->send_mail($l_aaa_id, $l_and_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $l_r_aaa, $l_r_and, $tagword, $email, $prod_name);
}
}
}
This CodeIgniter controller is runs every day and I get this running (Cronjob) for too long using almost nothing from the CPU and RAM (RAM is at 400M/4.25G and CPU at ONLY 0.7%-1.3%).
I wonder if there's an option to split all foreach loops to smaller threads (and I'm not sure if forking will do here) and run all the foreach loops in parallel but in a way that it wont get my server crashing.
I'm no DevOps and really interested learning - What should I do in this case?
I am using PHP4 (cannot upgrade) to query around 2,000 accounts but it's bringing back different results each time I refresh the page. If I shrink the number down to around 800 the results are still different each time, if I move down to around a dozen then I get the same results each time. Please can anyone advise?
<?php
set_time_limit(0);
$user = "CN=Account Name,OU=Users,OU=Helpdesk,OU=Group IT,DC=domain,DC=co,DC=uk";
$psw = "PasswordHere";
$csv = file('AD-Managers.csv');
foreach ($csv as $line){
$names = explode(",",$line);//explode by commas
$managerExists = "0";
$managerUPN = $names[4];
$managerSearch = "userprincipalname=".$managerUPN;
$search = "userprincipalname=".$userUPN;
$server = "jpr-ads-01s.jpress.co.uk";
$dn = "DC=domain,DC=co,DC=uk";
$ds=ldap_connect($server) or die("Could not connect to {$ldaphost}");
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($ds, LDAP_OPT_REFERRALS,0);
if($r=ldap_bind($ds, $user , $psw)){ //using bind as I will be updating accounts once I get it working
$sr=ldap_search($ds, $dn, $managerSearch);
$data = ldap_get_entries($ds, $sr);
//array shift as the first result in the array is NULL
$daa = array_shift($data);
foreach($data as $userData){
if (strpos($userData["dn"], 'Google Apps') == false){//make sure it's not a contact
$managersName = $userData["distinguishedname"][0];
$managerExists = "1";
break; //stop the loop if the user is found
}
}
}
ldap_close($ds);
if($managerExists == "1"){
echo "manager: ".$managerUPN;
echo "<br />";
}
else{
echo "manager not found: ".$managerUPN;
echo "<br />";
}
}
?>
sample of CSV:
1234567,John Smith,JOHN SMITH,john.smith#domain.co.uk,johns.manager#domain.co.uk,ABC1234,1,,,,,,,,,,,,
8901234,Jane Doe,JANE DOE,jane.doe#domain.co.uk,janes.manager#domain.co.uk,DEF7890,2,,,,,,,,,,,,
Sample result 1:
manager not found: johns.manager#domain.co.uk
manager not found: janes.manager#domain.co.uk
But I could refresh the page instantly and get:
manager: johns.manager#domain.co.uk
manager: janes.manager#domain.co.uk
Using an addon of FPDF, I am printing labels using PHP/MySQL (http://www.fpdf.de/downloads/addons/29/). I'd like to be able to have the user select how many labels to print. For example, if the query puts out 10 records and the user wants to print 3 labels for each record, it prints them all in one set. 1,1,1,2,2,2,3,3,3...etc. Any ideas?
<?php
require_once('auth.php');
require_once('../config.php');
require_once('../connect.php');
require('pdf/PDF_Label.php');
$sql="SELECT $tbl_members.lastname, $tbl_members.firstname,
$tbl_members.username, $tbl_items.username, $tbl_items.itemname
FROM $tbl_members, $tbl_items
WHERE $tbl_members.username = $tbl_items.username";
$result=mysql_query($sql);
if(mysql_num_rows($result) == 0){
echo "Your search criteria does not return any results, please try again.";
exit();
}
$pdf = new PDF_Label("5160");
$pdf->AddPage();
// Print labels
while($rows=mysql_fetch_array($result)){
$name = $rows['lastname'].', '.$rows['firstname';
$item= $rows['itemname'];
$text = sprintf(" * %s *\n %s\n", $name, $item);
$pdf->Add_Label($text);
}
$pdf->Output('labels.pdf', 'D');
?>
Assuming that a variable like $copies is an integer of how many copies they want made, I would make the following modification:
// Print labels
while( $row = mysql_fetch_array( $result ) ){
// Run Once for Each Result
$name = $row['lastname'].', '.$row['firstname'];
$item = $row['itemname'];
$text = sprintf(" * %s *\n %s\n", $name, $item);
if( isset( $copies ) ) {
// The Copies Variable exists
for( $i=0 ; $i<$copies ; $i++ ) {
// Run X times - Once for each Copy
$pdf->Add_Label($text);
}
} else {
// The Copies Variable does not exist - Assume 1 Copy
$pdf->Add_Label($text);
}
}
This should provide the required functionality.