Related
I'm trying to build a mail client with php and I get an issue when moving the e-mails from mail server to my database.
I'm using imap_fetchbody function. However, when I try to count(using imap_num_msg) or get the headers(including "0" on the 'section' parameter of imap_fetchbody) it does recognize all emails, without the body obviously. Database is local.
function getEmails(){
$query = "SELECT * FROM users";
$result = mysqli_query($this->connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$imapResource = imap_open($row["mailbox"], $row["usernamemail"], $row["passwordmail"], NULL) or die ('IMAP connection error');
}
$body_count = imap_num_msg($imapResource);
echo "There is a total of " . $body_count . " emails in your inbox. <br>"; // This counts REAL total amount of emails
$emails = imap_search($imapResource, "ALL");
rsort($emails);
if(!empty($emails)){
foreach($emails as $email){
// Fetch mail content
$overview = imap_fetch_overview($imapResource, $email, 0);
$overview = $overview[0];
$structure = imap_fetchstructure($imapResource, $email);
$attachments = array();
$id = $overview->uid;
$date = $overview->date;
$from = $overview->from;
$to = $overview->to;
$subject = $overview->subject;
$seen = $overview->seen;
if ($seen == 0){
$seen = "Not Seen";
} else{
$seen = "Seen";
}
$body = imap_fetchbody($imapResource, $email, "1", FT_PEEK);
// Check duplicates before uploading
$checkQuery = "SELECT ID FROM emails";
$result = mysqli_query($this->connection, $checkQuery);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)){
$testID = (string)$id;
if($testID !== $row["ID"]){
// Input into DB
$query = "INSERT INTO emails (ID, Date_recieved, From_email, To_email, Subject, Body, Type, Seen) VALUES ('$id', '$date', '$from', '$to', '$subject', '$body', '$emailType', '$seen')";
mysqli_query($this->connection, $query);
} else {
break;
}
}
} else{
// Input into DB
$query = "INSERT INTO emails (ID, Date_recieved, From_email, To_email, Subject, Body, Type, Seen) VALUES ('$id', '$date', '$from', '$to', '$subject', '$body', '$emailType', '$seen')";
mysqli_query($this->connection, $query);
}
}
}
The goal is for all emails to be inserted into the database and then pulled out for display and managed by user
Fixed The problem was special characters in Email's Subject (single-quote).
Noticed after setting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
To fix use mysqli_real_escape_string.
Fixed The problem was special characters in Email's Subject (single-quote). Noticed after setting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
To fix use mysqli_real_escape_string.
I am using php mysql pdo in here and trying to concatenate fname and lname but nothing going right am encountering {"error":true,"error_msg":"Unknown error occurred in registration!"} ..plzz help me out,pardon me if am wrong
.php
<?php
/*
starts with database connection
and gives out the result of query
in json format
*/
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
//proceed if fields are not empty
if (!empty($_POST['salutation']) && !empty($_POST['fname']) && !empty($_POST['mname']) && !empty($_POST['lname']) && !empty($_POST['pob']) && !empty($_POST['dob']) && !empty($_POST['qualification']) && !empty($_POST['pg']) && !empty($_POST['pgy']) && !empty($_POST['graduation']) && !empty($_POST['gy']) && !empty($_POST['schooling']) && !empty($_POST['sy']) && !empty($_POST['religion']) && !empty($_POST['caste']) && !empty($_POST['subcaste']) && !empty($_POST['familyname']) && !empty($_POST['fathername']) && !empty($_POST['mothername']) && !empty($_POST['brothers']) && !empty($_POST['sisters'])){
//reciving the post parameters
$salutation =$_POST['salutation'];
$fname = trim($_POST['fname']);
$mname = trim($_POST['mname']);
$lname = trim($_POST['lname']);
$pob = trim($_POST['pob']);
$dob = trim($_POST['dob']);
$qualification = trim($_POST['qualification']);
$pg = trim($_POST['pg']);
$pgy = trim($_POST['pgy']);
$graduation = trim($_POST['graduation']);
$gy = trim($_POST['gy']);
$schooling = trim($_POST['schooling']);
$sy = trim($_POST['sy']);
$religion = trim($_POST['religion']);
$caste = trim($_POST['caste']);
$subcaste = trim($_POST['subcaste']);
$familyname = trim($_POST['familyname']);
$fathername = trim($_POST['fathername']);
$mothername = trim($_POST['mothername']);
$brothers = trim($_POST['brothers']);
$sisters = trim($_POST['sisters']);
/*
validation process
begins from here
*/
// create a new user profile
$user = $db->storeUserProfile($salutation, $fname, $mname, $lname, $pob, $dob, $qualification, $pg, $pgy, $graduation, $gy, $schooling, $sy, $religion, $caste, $subcaste, $familyname, $fathername, $mothername, $brothers, $sisters);
if ($user){
// user stored successfully as post params passed
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["salutation"] = $user["salutation"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["mname"] = $user["mname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["pob"] = $user["pob"];
$response["user"]["dob"] = $user["dob"];
$response["user"]["qualification"] = $user["qualification"];
$response["user"]["pg"] = $user["pg"];
$response["user"]["pgy"] = $user["pgy"];
$response["user"]["graduation"] = $user["graduation"];
$response["user"]["gy"] = $user["gy"];
$response["user"]["schooling"] = $user["schooling"];
$response["user"]["sy"] = $user["sy"];
$response["user"]["religion"] = $user["religion"];
$response["user"]["caste"] = $user["caste"];
$response["user"]["subcaste"] = $user["subcaste"];
$response["user"]["familyname"] = $user["familyname"];
$response["user"]["fathername"] = $user["fathername"];
$response["user"]["mothername"] = $user["mothername"];
$response["user"]["brothers"] = $user["brothers"];
$response["user"]["sisters"] = $user["sisters"];
$response["user"]["uuid"] = $user["unique_id"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}else{
//missing the required fields
$response["error"] = true;
$response["error_msg"] = "Please fill all the required parameters!";
echo json_encode($response);
}
?>
this is the database part using pdo.
php
public function storeUserProfile($salutation, $fname, $mname, $lname, $pob, $dob, $qualification, $pg, $pgy, $graduation, $gy, $schooling, $sy, $religion, $caste, $subcaste, $familyname, $fathername, $mothername, $brothers, $sisters){
try {
$characters = '0123456789';
$uuid = '';
$random_string_length = 6;
for ($i = 0; $i < $random_string_length; $i++) {
$uuid .= $characters[rand(0, strlen($characters) - 1)];
}
$sql = "INSERT INTO profile_info(salutation, fname, mname, lname, fullname, pob, dob, qualification, pg, pgy, graduation, gy, schooling, sy, religion, caste, subcaste, familyname, fathername, mothername, brothers, sisters, unique_id, created_at) VALUES ( '$salutation', '$fname', '$mname', '$lname', '$fname'.', '.'$lname', '$pob', '$dob', '$qualification', '$pg', '$pgy', '$graduation', '$gy', '$schooling', '$sy', '$religion', '$caste', '$subcaste', '$familyname', '$fathername', '$mothername', '$brothers', '$sisters', '$uuid', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
//concatenate the strings
$sql = "UPDATE profile_info SET fullname = CONCAT(fname, ', ', lname)";
$dbh = $this->db->prepare($sql);
$dbh->execute();
// get user details
$sql = "SELECT * FROM profile_info WHERE familyname = '$familyname' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
}
catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
return false;
}
The concatenation of first name and last name in your INSERT query is incorrect. Use a $fullname variable to specify full name of the person, and use that variable in your INSERT query. That way you won't have to update the row because you have already inserted the row with the correct full name.
Your code should be like this:
// your code
$fullname = $fname . ", " . $lname;
$sql = "INSERT INTO profile_info(salutation, fname, mname, lname, fullname, pob, dob, qualification, pg, pgy, graduation, gy, schooling, sy, religion, caste, subcaste, familyname, fathername, mothername, brothers, sisters, unique_id, created_at) VALUES ( '$salutation', '$fname', '$mname', '$lname', '$fullname', '$pob', '$dob', '$qualification', '$pg', '$pgy', '$graduation', '$gy', '$schooling', '$sy', '$religion', '$caste', '$subcaste', '$familyname', '$fathername', '$mothername', '$brothers', '$sisters', '$uuid', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
// get user details
$sql = "SELECT * FROM profile_info WHERE familyname = '$familyname' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
// your code
If I understand the issue properly, the values are not being inserted because you are executing, instead, a SELECT statement. SELECT statements do not modify table data. You would instead do something like this:
UPDATE profile_info SET fullname = CONCAT(fname, ', ', lname);
Note, this would update the entire table....
This will fill in a pre-existing column with the new concatenated value made from the fname and lname values of each row.
Of course, if your table does not currently have a column for fullname, add one:
ALTER TABLE profile_info ADD COLUMN fullname varchar(25);
UPDATE
Take this line out:
$sql = UPDATE profile_info SET fullname = CONCAT(fname, ', ', lname);
And change this line:
$sql = "INSERT INTO profile_info(salutation, fname, mname, lname, fullname, pob, dob, qualification, pg, pgy, graduation, gy, schooling, sy, religion, caste, subcaste, familyname, fathername, mothername, brothers, sisters, unique_id, created_at) VALUES ( '$salutation', '$fname', '$mname', '$lname', '$fname'.', '.'$lname', '$pob', '$dob', '$qualification', '$pg', '$pgy', '$graduation', '$gy', '$schooling', '$sy', '$religion', '$caste', '$subcaste', '$familyname', '$fathername', '$mothername', '$brothers', '$sisters', '$uuid', NOW())";
You'll see I added 'fullname' in the columns list, and this in the values list: '$fname'.', '.'$lname',
using PHP's concatenation operator .
The correct way to accomplish this is to simply concatenate the values and insert them at the very same time you insert the rest of the values. Let me know if that does it for you.
A side note, editing your original code does make the question more confusing for viewers who came in after the edits were made. Consider adding notes about any edits to the code, instead of editing the original example.
I am trying to fetch my emails, parse them, and insert them into my database. I am pretty far along on parsing, but the inserting part is not going well.
$headerost = 'imap.gmail.com';
$user = 'email#gmail.com ';
$pass = 'password';
$port = 993;
$protocol = "/imap/ssl";
$connect = imap_open("{{$headerost}:{$port}{$protocol}}INBOX", $user, $pass);
if (!$connect) die("Failed: $connect");
$count = imap_num_msg($connect);
for ($i = 1; $i <= $count; $i++) {
$header = imap_header($connect, $i);
$to = $header->to[0];
$from = $header->from[0];
$date = $header->date;
$date1 = date_create($date);
$date2 = date_format($date1, 'l - F jS, Y - g:i A');
$mailbox = quoted_printable_decode($from->mailbox);
$headerost = $from->host;
$email = "$mailbox#$headerost";
$mailbox1 = $to->mailbox;
$headerost1 = $to->host;
$email1 = "$mailbox1#$headerost1";
$letter = imap_fetch_overview($connect, $i);
$subj = imap_utf8( $letter[0]->subject);
$message = quoted_printable_decode(imap_fetchbody($connect, $i,1));
$query2 = "
SELECT *
FROM email
WHERE `email` = '$email'
AND 'date' = '$date2';
";
$result2 = mysql_query($query2);
$num = mysql_num_rows($result2);
$coming = "Client";
if ($num == 0) {
mysql_query ("
INSERT INTO email (
coming,
email,
date,
actualdate,
subject,
message
)
VALUES (
'$coming',
'$email',
'$date2',
'$date2',
'$subj',
'$message'
)
");
}
}
The $message is sometimes displaying the whole message, but sometimes it also displays replies, and sometimes it just displays gibberish. actual date is a date format in the MYSQL, and its entering at 00-00-0000. Email is entering as 0. $date2, $subj, and $coming are entering properly.
I have a text file, who's value i have put into arrays,
this is the php code:
<?php
$homepage = file_get_contents('hourlydump.txt');
$x = explode('|', $homepage);
$desc = array();
$cat = array();
$link = array();
$m = 1;
$n = 2;
$p = 3;
for ($i = 1; $i <= count($x) / 4; $i++) {
$m = $m + 4;
$desc[] = $x[$m];
$n = $n + 4;
$cat[] = $x[$n];
$p = $p + 4;
if ($x[$p])
$link[] = $x[$p];
}
echo "<pre>";
print_r($desc);
print_r($cat);
print_r($link);
?>
output is like:
Array
(
[0] => Kamal Heer - Facebook Official Video 720p Dual Audio [Hindi + Punjabi]76 mb by rANA.mkv
[1] => 50 HD Game Wallpapers Pack- 1
)
Array
(
[0] => Movies
[1] => Other
)
Array
(
[0] => http://kickass.to/kamal-heer-facebook-official-video-720p-dual-audio-hindi-punjabi-76-mb-by-rana-mkv-t7613070.html
[1] => http://kickass.to/50-hd-game-wallpapers-pack-1-t7613071.html
)
//
//
//
anyone please help me i dont know how to insert the values of these three arrays $desc, $cat and $link
into mysql table, columns named description, category, link
i know simple insert queries but dont how to deal with these arrays.
I will give you an example of how basic database connection is made and the insert is completed, this is for illustrative purpose only. You should reorganize this code inside a class so that every insert statement doesn't create a PDO object but re-use the object created before.
function insertItem($desc, $cat, $link) {
$dbh = new PDO("mysql:host=host;dbname=db", $user, $pass);
$sql = "INSERT INTO table (description, category, link) VALUES (:desc, :cat, :link)";
$sth = $dbh->prepare($sql);
$sth->bindValue(":desc", $desc);
$sth->bindValue(":cat", $cat);
$sth->bindValue(":link", $link);
$sth->execute();
}
You can use a for statement.
for($x =0, $num = count($desc); $x < $num; $x++){
// build you query
$sql = "INSERT into your_table (description, category, link) values ".
"(".$db->quote($desc[$x]).",".$db->quote($cat[$x]).",".
$db->quote($link[$x].")";
$db->query($sql);
}
Of course you will have to use the sanitation/quoting methods appropriate for your chosen database api.
Here is a simple sample to read your file as is from the website you retrieve it as well as inserting it to the database sanitizing the data:
<?php
// fill with your data
$db_host = 'localhost';
$db_user = '';
$db_pass = '';
$db_name = '';
$db_table = 'myTable';
$file = "hourlydump.txt.gz";
if($filehandle = gzopen($file, "r"))
{
$content = gzread($filehandle, filesize($file));
gzclose($file);
}
else
die('Could not read the file: ' . $file);
$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if($con->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$sql = "INSERT INTO $db_table (description, category, link) VALUES (?, ?, ?)";
if (!$insert = $con->prepare($sql))
die('Query failed: (' . $con->errno . ') ' . $con->error);
foreach (explode("\n", $content) as $line)
{
list($md5hash,$desc,$cat,$link,$torrent) = explode("|", $line);
if (!$insert->bind_param('sss',$desc,$cat,$link))
echo 'Binding parameters failed: (', $insert->errno, ') ', $insert->error;
if (!$insert->execute())
echo 'Insert Error ', $insert->error;
}
$insert->close();
$con->close();
NOTE: you may want to check if the file was loaded with success, if the fields from the explode exist or not to prevent further problems but in general this should work just fine.
Also you may want to change the $sql to reflect your MySQL table aswell as the $db_table at the top.
UPDATE: to insert all values change this:
$sql = "INSERT INTO $db_table (description, category, link) VALUES (?, ?, ?)";
To:
$sql = "INSERT INTO $db_table (md5, description, category, link, torrent) VALUES (?, ?, ?, ? ,?)";
And this:
if (!$insert->bind_param('sss',$desc,$cat,$link))
To:
if (!$insert->bind_param('sssss',$md5hash,$desc,$cat,$link,$torrent))
Note above the s for each item you need a s you have 5 items so 5 s's the S means string, D double, I integer, B blob you can read more at about it here.
Also note the $sql for each item we will use on the bind_param we have a ?.
Try this. I am assuming that only these much of values are there for insertion
for($i = 0;$i<2;$++) {
mysqli_query("INSER INTO tablename values(description,category,link) VALUES('$desc[$i]'
,'$cat[$i]','$link[$i]')");
}
You can build your query while you're doing you calculations:
$query = "INSERT INTO `table` (`description`, `category`, `link`) VALUES ";
for ($i = 1; $i <= count($x) / 4; $i++) {
$m = $m + 4;
$query .= "('".$x[$m];
$n = $n + 4;
$query .= "','".$x[$n];
$p = $p + 4;
if ($x[$p]) $query .= "','".$x[$p]."'),";
else $query .= "',NULL),";
}
$query = substr($query, 0, -1);//get rid of last comma
mysqli_query($query);
You can also build the arrays along with the query if you need to:
$query = "INSERT INTO `table` (`description`, `category`, `link`) VALUES ";
for ($i = 1; $i <= count($x) / 4; $i++) {
$m = $m + 4;
$desc[] = $x[$m];
$query .= "('".$x[$m];
$n = $n + 4;
$cat[] = $x[$n];
$query .= "','".$x[$n];
$p = $p + 4;
if ($x[$p]){
$link[] = $x[$n];
$query .= "','".$x[$p]."'),";
} else {
$link[] = $x[$n];
else $query .= "',NULL),";
}
$query = substr($query, 0, -1);//get rid of last comma
mysqli_query($query);
make the array to a string
$description = json_encode($desc);
$category = json_encode($cat);
$link = json_encode($link);
then insert these values to database
At the time of fetching
Use json_decode to get the array again from the string
Hi I have a jqgrid setup with a custom action button that sends selected rows to a database. I have everything working except that it posts the data 7 times per each row select where I only want it posted once per selected row. Please any and all help appreciated. JQGrid, How to post JSON string to PHP to Process and send to Database?
$decarr= array(
['id'] =>
518
['name'] =>
'Brochure for amada'
['id_continent'] =>
' Ramon'
['lastvisit'] =>
'5/15/2013'
['cdate'] =>
'5/29/2013'
['ddate'] =>
'5/31/2013'
['email'] =>
'Files'
)
PHP:
//First decode the array
$arr = $_POST["json"];
$decarr = json_decode($arr, true);
$count = count($decarr);
$values = array(); // This will hold our array values so we do one single insert
for ($x=0; $x < $count; $x++){
$newrec = $decarr;
$id = $newrec['id']; $id = mysql_real_escape_string($id);
$name = $newrec['name']; $name = mysql_real_escape_string($name);
$id_continent = $newrec['id_continent']; $id_continent = mysql_real_escape_string($id_continent);
$email = $newrec['email']; $email = mysql_real_escape_string($email);
$lastvisit = $newrec['lastvisit']; $lastvisit = mysql_real_escape_string($lastvisit);
$cdate = $newrec['cdate']; $cdate = mysql_real_escape_string($cdate);
$ddate = $newrec['ddate']; $ddate = mysql_real_escape_string($ddate);
// Create insert array
$values[] = "('".$id."', '".$name."', '".$id_continent."', '".$lastvisit."','".$cdate."','".$ddate."','".$email."' )";
}
// Insert the records
$sql = "INSERT INTO finish (id, name, id_continent, lastvisit,cdate,ddate, email)
VALUES ".implode(',', $values);
$result = mysql_query($sql, $con) or die(mysql_error());
?>
Fixed! I figured out the the variables were reiterated over and over with the other lines. Much love y'all.
//First decode the array
$arr = $_POST["json"];
$decarr = json_decode($arr, true);
$count = count($decarr);
for ($x=0; $x < $count; $x++){
$newrec = $decarr;
$id = $newrec['id'];
$name = $newrec['name'];
$id_continent = $newrec['id_continent'];
$email = $newrec['email'];
$lastvisit = $newrec['lastvisit'];
$cdate = $newrec['cdate'];
$ddate = $newrec['ddate'];
}
// Create insert array
$values[] = "('".$id."', '".$name."', '".$id_continent."', '".$lastvisit."','".$cdate."','".$ddate."','".$email."' )";
// Insert the records
$sql = "INSERT INTO finish (id, name, id_continent, lastvisit,cdate,ddate, email)
VALUES ".implode(',', $values);
$result = mysql_query($sql, $con) or die(mysql_error());
?>