imap_open parse and insert into database - php

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.

Related

php mysql trying to use empty to only add a new record in table if a primary key exists in a different table

I am trying to only allow a submission via the form only if a party_id exists in a table using empty, here is my code at the moment it is still allowing everything through even if there is no party_id.
Any help would be great.
if($_SERVER["REQUEST_METHOD"]== "POST") {
$party_id = (int)$_POST["partyid"];
$name = $_POST["name"];
$date = $_POST["date"];
$length = (int)$_POST["length"];
$sql = "SELECT * FROM `party` WHERE `party_id`='" . $party_id . "'";
$res = mysqli_query($link, $sql);
if(empty($party_id)) { #Were any records found?
print '<p>No Parties with that ID found! please press the back button to select another party</p>';
} else {
$record = mysqli_fetch_assoc($res);
$party_name = $record["party_name"];
$price = $record["price"];
$cost = $price * $length;
$bookable = true;
$sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database");
A simpler way might be to just check if the query returned any results like this.
if($_SERVER["REQUEST_METHOD"]== "POST") {
$party_id = (int)$_POST["partyid"];
$name = $_POST["name"];
$date = $_POST["date"];
$length = (int)$_POST["length"];
$sql = "SELECT * FROM `party` WHERE `party_id`='$party_id'";
$res = mysqli_query($link, $sql);
if ( mysqli_num_rows($res ) == 0 ) {
print '<p>No Parties with that ID found! please press the back button to select another party</p>';
} else {
$record = mysqli_fetch_assoc($res);
$party_name = $record["party_name"];
$price = $record["price"];
$cost = $price * $length;
$bookable = true;
$sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database");

Unknown column 'E5V7D24M10Y2015' in 'where clause'

I have the code below to update (more 'add to') a row in a database. I have read a few very similar posts, but still can't see where I'm going wrong...
I am getting the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''EventID' = '2' WHERE GameID = 'E2V1D24M10Y2015' AND PlayerID = '55'' at line 1
In this case, 'E5V7D24M10Y2015' is the value of $GameID. I am looking for a column called GameID where the value is E5V7D24M10Y2015, not a column of that name. Please tell me why my $sql is looking for a column named after the value it is looking for.
Each time the function runs the count($Runners) will be different and the values in each variable will be different. That is why I have the SQL in a loop.
if ($formtype == "gameresults"){
$Runners = $_POST['runners'];
$event = $_POST['event'];
$eid = $_POST['eid'];
$vid = $_POST['vid'];
$GameID = $_POST['GameID'];
$date = $_POST['date'];
$season = $_POST['season'];
$region = $_POST['region'];
$notes = $_POST['notes'];
$kev = "kev#email.com";
$email = $_POST['manager'];
$notes = wordwrap($notes,70);
$subject = ("Results for " . $event);
$tix = "";
$cashs = "";
for ($x = 1; $x < ($Runners + 1); $x++){
$ID = $_POST['ID' . $x];
$Name = $_POST['Name' .$x];
$Place = $_POST['Place'.$x];
$Points = $_POST['Points'.$x];
$Cash = $_POST['Cash'.$x];
$Ticket = $_POST['Ticket'.$x];
$vn = $_POST['vn'];
$buyin = $_POST['buyin'];
$data = array($eid,$vid,$region,$buyin,$GameID,$date,$season,$ID,$Name,$Place,$Points,$Ticket,$Cash,$Runners);
$fields = array('EventID','VenueID','Region','Buyin','GameID','Date','Season','PlayerID','Name','Position','Points','Ticket?','Cash','Runners');
for ($x = 0; $x < (count($data) - 1); $x++){
$sql = "UPDATE results SET '$fields[$x]' = '$data[$x]' WHERE GameID = '$GameID' AND PlayerID = '$ID'";
$res = mysqli_query($dbcon, $sql) or die("Update failed. <br>" . mysqli_error($dbcon));
}
You could modify your code to be more clear. I did example but I did not map all the fields so you need to adjust it.
$eid = 4;
$vid = 5;
$region = 'aa';
$buyin = 'asd';
$gameID = 5;
$date = 5;
$playerID = 10;
$fields = array(
'EventID' => $eid,
'VenueID' => $vid,
'Region' => $region,
'Buyin' => $buyin,
'GameID' => $gameID,
'PlayerID'=> $playerID,
'Date' => $date,
);
$numItems = count($fields);
$query = "UPDATE `results` SET ";
$i = 0;
foreach($fields as $name => $value) {
++$i;
if($name == 'GameID' || $name == 'PlayerID') {
continue;
}
$query .= sprintf(" `%s` = '%s'%s ", $name, $value, ($i === $numItems ? "": ","));
}
$query .= sprintf(" WHERE `GameID` = '%d' AND `PlayerID` = '%d'", $fields['GameID'], $fields['PlayerID']);
echo $query;
Fields can be maped via $key => $value and then used in foreach loop. Also using sprintf() makes is more clear to read. However, the best option would be using prepared statements.
Also you don't need to make multiple UPDATE queries, just SET more parameters in one query.
$data = array($eid,$vid,$region,$buyin,$GameID,$date,$season,$ID,$Name,$Place,$Points,$Ticket,$Cash,$Runners);
$fields = array('EventID','VenueID','Region','Buyin','GameID','Date','Season','PlayerID','Name','Position','Points','Ticket?','Cash','Runners');
for ($x = 0; $x < (count($data) - 1); $x++){
$sql = "UPDATE results SET " . $fields[$x] . " = '$data[$x]' WHERE results.GameID = $GameID AND results.PlayerID = $ID";
$res = mysqli_query($dbcon, $sql) or die("Update failed. <br>" . mysqli_error($dbcon));
}
Try this by specifying alias.

select value into variable using input from form

Hi i am having an issue selecting a value form my table into a variable in the PHP so that I can calculate the cost of something
here is the code I have so far I want to be able to select a "cost" value from the table C_price where the values of I_type and a_type match
E.g. the table structure looks like this
ID=1,A_type=line,I_type=Head,cost=5
if on the form i enter line and head
i need to be able to get the value 5 in to a venerable i can use in calculations and insert into another table AKA i need to get cost into a variable somehow
the following was my try and i need help im new at all this so please help
$E_C;
$T_cost = "1";
$date = date("d.m.y");
$name = $_POST["from"];
$email = $_POST["email"];
$ref = $_POST["link"];
$i_type = $_POST["i_type"];
$a_type = $_POST["a_type"];
$extra = $_POST["extra"];
$des = $_POST["description"];
$BG = $_POST["BG"];
$bg_type = $_POST["BGtype"];
$msg = $_POST["message"];
$auto_reply = ("thanks for the email we will get back to you as soon as we can about the cost and how you can pay");
$msg = wordwrap($msg, 70);
$host = "localhost";// hostname
$USER = "root";// username
$PASS = "Password";// password
$DBNAME = "andrea";// databace name
$tbl_name = "c_price";// table name
$con = mysqli_connect("localhost", $USER, $PASS, $DBNAME)or die("mySQL server connection failed");
$all = "SELECT cost FROM C_price WHERE a_type=$a_type,i_type=$i_type";
$result = mysqli_query($con,$all) or die("Error getting total storse");
while($row = mysqli_fetch_array($result))
{
echo $row['cost'];
}
if ($a_type = 'waist' && $extra='Y')
{
$E_C = $cost * .3;
}
elseif ($a_type = 'knee' && $extra='Y')
{
$E_C = $cost * .35;
}
elseif ($a_type ='full' && $extra='Y')
{
$E_C = $cost * .4;
}
else
{
$E_C = 0;
}
$T_cost = $cost + $E_C;
if ($BG = 'y')
{
$T_cost = $T_cost + 10;
}
You can't use mysqli and mysql at a same time.. Mysqli is a class... So first change that things...
while($row = mysqli_fetch_array($result))
{
echo $row['cost'];
}
$news1 = mysqli_result($result, 0); // 0 is the index of the field, not the row
echo $news1;
echo $cost;`
Query should be like this...
$all = "SELECT cost FROM C_price WHERE a_type='$a_type'and i_type='$i_type'";
You cant mix mysql and mysqli
change this line In the while loop and add for error mysqli_error
$news1 = mysql_result($result, 0);
$news1 = mysqli_result($result) or die(mysqli_error());
and your query is wrong as well and A_type is not same as A_type and same goes for I_type as well
$all = "SELECT cost FROM C_price WHERE a_type=$a_type,i_type=$i_type";
//Change it to
$all = "SELECT cost FROM C_price WHERE A_type='$a_type'and I_type='$i_type'";
//and A_type is not same as a_type and same goes for I_type as well

imap_fetchbody() text/html section

I'm trying to develop a E-Mail-Provider-Script.
With the following function the E-Mails should be saved in the MySQL database directly, but my efforts to save only the TEXT / HTML section failed. What am I doing wrong( likely with imap_fetchbody() )?
function getEmailsImap($mailserver, $port, $user, $pass)
{
$imap = imap_open( "{" . $mailserver . ":" . $port . "}INBOX", $user, $pass );
$check = imap_mailboxmsginfo($imap);
$totalrows = imap_num_msg($imap);
//iterate through all unread mails
for ($index = 0; $index < $totalrows; $index++)
{
$header = imap_header($imap, $index + 1);
//get mail subject
$subject = $header->subject;
//get mail sent date
$date = date(DateTime::ISO8601 , $header->udate);
//get email authors
$email = "{$header->from[0]->mailbox}#{$header->from[0]->host}";
//get body
$body = imap_fetchbody($imap, $index+1, "1.2"); /*** I think this might be the mistake **/
//get user
$to = $header->to[0]->mailbox;
$user = explode("#", $to)[0];
$id = (int)mysql_fetch_row(mysql_query("SELECT `id` FROM `fd_emails` ORDER BY `id` DESC LIMIT 1"))[0];
$new_id = $id+1;
$sql = mysql_query("INSERT INTO `fd_emails` (`id`, `subject`, `text`, `sender`, `user`, `date`)
VALUES ('$new_id', '$subject', '$body', '$email', '$user', '$date');");
imap_delete($imap, $index + 1);
}
//close connection to mailbox
imap_expunge($imap);
imap_close($imap);
return true;
}
Many thanks in advance.
As per the php documentation
string imap_fetchbody ( resource $imap_stream , int $msg_number , string $section [, int $options = 0 ] )
The number must have string type only. Using a integer type would raise an error.

Grab info from multiple sql tables and put into one using php

At the moment this code updates the user info in MYSQLTABLE1. What I also want done is user info to be copied to WMYSQLTABLE which I can do but I also want a code from MYSQLTABLE2 to be copied over into a column in WMYSQLTABLE as well. Here is the part I need changing:
$sql_insert2 = "INSERT INTO ".WMYSQLTABLE2."(ip,date,address)values
('','$ip','$date','$address')";
$res_insert2 = mysql_query($sql_insert2)or die(mysql_error());
//Need to also insert code from first row from column named 'codes' in MYSQLTABLE2.
Actual code, it's a bit messy at the moment and the if/else statements do the exact same at the moment. It works but I get the error " Column count doesn't match value count at row 1" because I cannot fill the last column with the code from MYSQLTABLE2.
<?php
include("includes/config.php");
include("includes/mysql.php");
include("amount.php");
if(isset($_POST['func']))
{
$address = $_POST['address'];
$ip = $_POST['ip'];
$date = $_POST['date'];
$time = $_POST['time'];
$price = $_POST['price'];
$increment = $_POST['increment'];
$id = $_POST['id'];
$num = 0;
$sql_check_address = "SELECT * FROM ".MYSQLTABLE1." WHERE address='$address'";
$res_check_address = mysql_query($sql_check_address)or die(mysql_error());
$num = mysql_num_rows($res_check_address);
$row = mysql_fetch_assoc($res_check_address);
if($num > 0)
{
$address = $row['address'];
$ip = $row['ip'];
$date = $row['date'];
$oldprice = $row['price'];
$id = $row['id'];
$newprice = $oldprice - $payAmount*200;
$newinc = $increment - 200;
$sql_update1 = "UPDATE ".MYSQLTABLE1." SET ip='$ip',date='$date',price='$newprice',increment='$newinc',address='$address' WHERE id='$id'";
$res_update1 = mysql_query($sql_update1)or die(mysql_error());
/////////////////Insert user info and copy code from MYSQLTABLE2 to WMYSQLTABLE2
$sql_insert2 = "INSERT INTO ".WMYSQLTABLE2."(ip,date,address)values
('','$ip','$date','$address')";
$res_insert2 = mysql_query($sql_insert2)or die(mysql_error());
}
else{
$address = $row['address'];
$ip = $row['ip'];
$date = $row['date'];
$oldprice = $row['price'];
$id = $row['id'];
$newprice = $oldprice - $payAmount*200;
$newinc = $increment - 200;
$sql_update = "UPDATE ".MYSQLTABLE1." SET ip='$ip',date='$date',price='$newprice',increment='$newinc',address='$address' WHERE id='$id'";
$res_update = mysql_query($sql_update)or die(mysql_error());
/////////////////Insert user info and copy code from MYSQLTABLE2 to WMYSQLTABLE2
$sql_insert2 = "INSERT INTO ".WMYSQLTABLE2."(ip,date,address)values
('','$ip','$date','$address')";
$res_insert2 = mysql_query($sql_insert2)or die(mysql_error());
e
}
}
Any help will be greatly appreciated.
The general form of the query would be:
$sql_insert = "INSERT INTO " . WMYSQLTABLE2 . "(code, ip, date, address)
SELECT code, '$ip', '$date', '$address'
FROM OtherTable
WHERE <put something here to select the row>";

Categories