Hi I have a table that records details which then after the record is saved I can use the link to update the diary. one field is a simple Job reference, the second is basically all the rest, name address etc inserted into a memo field in the diary, this is what I've come up with can I have some guidance please.
<?php
//record identifier date format 0000-00-00 same as server
$Dt = $_REQUEST['DT'];
// text output for appontment
$A = $_REQUEST['A'];
$B = $_REQUEST['B'];
$C = $_REQUEST['C'];
$D = $_REQUEST['D'];
$E = $_REQUEST['E'];
$F = $_REQUEST['F'];
$G = $_REQUEST['G'];
$H = $_REQUEST['H'];
$I = $_REQUEST['I'];
$J = $_REQUEST['J'];
$K = $_REQUEST['K'];
$L = $_REQUEST['L'];
$M = $_REQUEST['M'];
$N = $_REQUEST['N'];
// field names to reference
$APP = $_REQUEST['P'];
$JD = $_REQUEST['Q'];
// Field content
$JN = $_REQUEST['JID'];
$Desc = $"" . $A . "" . $B . " " . $C . ". " . $D . ", " . $E . " " . $F . " " . $G . " TF " . number_format($H,0, $decimal_point,"") . " " . $I . ", " . $J . " Walls, " . number_format($K,0, $decimal_point,"") . "Beds. " . $J . " " . $K . " boiler, with " . number_format($L,0, $decimal_point,"") . " radiators. notes " . $M . " observations " . $N . "";
?>
<?php
$servername = "localhost:3306";
$username = "xxxdjw";
$password = "xxxxxx";
$dbname = "xxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE masterdiary SET $APP ='$JN', $JD = '$Desc' WHERE date = '$dt'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Or would it be easier to try and write a trigger?
It is advisable to use trigger for this
Sample trigger given below
CREATE
TRIGGER blog_after_insert AFTER INSERT
ON blog
FOR EACH ROW BEGIN
IF NEW.deleted THEN
SET #changetype = 'DELETE';
ELSE
SET #changetype = 'NEW';
END IF;
INSERT INTO audit (blog_id, changetype) VALUES (NEW.id, #changetype);
END$$
Related
I duplicated a folder full of scripts and edited the contents.
ex: /scripts -> /script-new
When I run a php script from this new file I seem to be having some weird issues.
php -f /scripts-new/pulldata.php
When I do this it seems to be using some variables from the old script that I have changed in the code.
/scripts/pulldata.php
$dbtable = "validclickvc";
/scripts-new/pulldata.php
$dbtable = "valid_click_ads";
Here is the mysql command that I am running
$sql = "INSERT INTO " . $dbtable . " ( COLUMN_NAMES ) " . " VALUES ( COLUMN_VALUES )";
And in my error log:
Error: INSERT IGNORE INTO validclickvc VALUES ( '--' )
What might be causing this?
EDIT:
Here is the whole script if it helps!
<?php
// Set some variables to connect to the FTP
$yesterday = date("Ymd", strtotime( '-1 days' ));
$filename = "vc_report_" . $yesterday . ".csv";
$sourcefile = "/***/" . $filename;
$localfile = "php://output";
$ftpserver = "***";
$ftpusername = "***";
$ftppassword = "***";
// Set some variabled to connect to rhe database
$dbhost = "***";
$dbname = "***";
$dbtable = "valid_click_ads";
$dbusername ="***";
$dbpassword = "***";
$fielddelimiter = ",";
$linedelimiter = "\r\n";
// Try to connect to the ftp server
$conn = ftp_connect($ftpserver) or die("Could not connect");
echo "Connected to FTP. \n";
// Try to login to the ftp server
if (ftp_login($conn, $ftpusername, $ftppassword)) {
echo "Logged in to FTP. \n";
} else {
echo "FTP login unsuccessful. \n";
}
ob_start();
// Try to open download today's report
$file = ftp_get($conn, $localfile, $sourcefile, FTP_BINARY);
if ($file) {
$csvcontent = ob_get_contents();
echo "File read successfully. \n";
} else {
echo "File was not read successfully. \n";
}
// Close the file and the connection to the FTP
ftp_close($conn);
echo "File and connection to the FTP closed. \n";
// Connect to the database
$con = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbname);
if (!$con) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
} else {
echo "Connected to database. \n";
}
// Set row counter
$rows = 0;
// Set first
$first = true;
// Separate data by line
$lines = explode(PHP_EOL, $csvcontent);
// Insert lines of data
foreach ($lines as $line) {
if (!$first) {
$linearray = explode($fielddelimiter, $line);
print_r ($linearray);
$source_tag = $linearray[1];
if ( strpos( $source_tag, 'phone' ) !== false ) {
$source = "Smart Phone";
} else if ( strpos( $source_tag, 'desktop' ) !== false ) {
$source = "Desktop";
} else {
$source = "";
}
if ( $linearray[14] == "N/A" ) {
$tq = -1;
} else {
$tq = $linearray[14];
}
$sql = "SELECT affiliate_id, id, campaign_id, group_id, user_id, website_id FROM keywords WHERE affiliate_id = " . $linearray[7];
$result = $con->query($sql);
if ( $row = $result->fetch_assoc() ) {
$keyword_id = $row[ 'id' ];
$group_id = $row[ 'group_id' ];
$campaign_id = $row[ 'campaign_id' ];
$user_id = $row[ 'user_id' ];
$website_id = $row[ 'website_id' ];
} else {
$keyword_id = "";
$group_id = "";
$campaign_id = "";
$user_id = "";
$website_id = "";
}
$sql = "INSERT IGNORE INTO " . $dbtable . " ( market, source, device, searches, impressions, clicks, revenue, tq, website_id, user_id, campaign_id, group_id, affiliate_id, keyword_id ) " . " VALUES ( '" . $linearray[5] . "', " . $source . "', " . $linearray[4] . "', " . $linearray[8] . "', " . $linearray[9] . "', " . $linearray[10] . "', " . $linearray[12] . "', " . $tq . "', " . $website_id . "', " . $user_id . "', " . $campaign_id . "', " . $group_id . "', " . $affiliate_id . "', " . $keyword_id . "' )";
echo $sql;
if ($con->query($sql) === TRUE) {
$rows++;
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
} else {
$first = false;
}
}
$con->close();
echo "Inserted a total of " . $rows . " records.\n"
?>
I have a foreach to elaborate some values from my web site and I'd like to insert them into a mysql database.
My problem is where I have an array, because I don't know how to treat them in this case.
This is my code:
...
$titles = $html->find("a[class=in-match]"); // 1 per match
$result = $html->find("td[class=h-text-center]/a"); // 1
$best_bets = $html->find("td[class=table-matches__odds colored]/span/span/span"); // 1
$odds = $html->find("td[class=table-matches__odds]"); // 2
function print_odd($odd) {
if (array_key_exists('data-odd', $odd->attr)) {
return $odd->attr['data-odd'];
}
return $odd->children(0)->children(0)->children(0)->attr['data-odd'];
}
$c=0; $b=0; $o=0; $z=0; // two counters
foreach ($titles as $match) {
list($num1, $num2) = explode(':', $result[$c++]->innertext); // <- explode
$num1 = intval($num1);
$num2 = intval($num2);
$num3 = ($num1 + $num2);
if ($num3 > 1) {
$over15 = "OK";
} else {
$over15 = "NO";
}
echo "<tr><td class='rtitle'>".
"<td class='first-cell'>".$match->innertext."</td> ".
"<td>".$match->innertext."</td><td> ".$num1.'</td><td> : </td><td>'.$num2 . " / " . // <- example use
"<td class='first-cell'>".$num3 ."</td> " .
"<td class='first-cell'>".$over15 ."</td> " .
"<td class='odds'>".print_odd($odds[$b++]) . ";" .
"".print_odd($odds[$b++]) . ";" .
"".print_odd($odds[$b++]) . "</td>" .
"</td></tr><br/>";
$servername = "xx.xxx.xxx.xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO risultati (titles, scorehome, scoreaway, best_bets)
VALUES ('$match', '$num1', '$num2', '$odds');";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
When I run this, I don't get that 3 "$odds"
Thank you for your attention
EDIT So, I saved almost all data with my code but I have a problem with $odds (You can see my function print_odd). How could to save them?
Try the concept... Thanks
$columns = implode(", ",array_keys($insData));
$escaped_values = array_map('mysql_real_escape_string', array_values($insData));
$values = implode(", ", $escaped_values);
$sql = "INSERT INTO `fbdata`($columns) VALUES ($values)";
The PHP Code:
<?php
//Server Information
$servername = "localhost";
$dbusername = "USERNAME";
$password = "TOTALLYSECUREPASSWORD";
$dbname = "DEFINITELYADATABASE";
//Query Information
$guid = $_POST['GUID'];
$username = $_POST['USERNAME'];
$admin_username = $_POST['ADMIN_USERNAME'];
$ban_reason = $_POST['BAN_REASON'];
$ip = $_POST['IP'];
//Create Connection
$connection = mysqli_connect($servername, $dbusername, $password, $dbname);
//Check the Connection
if ($connection->connect_error){
die("Connection failed: " . $connection->connect_error);
}
//$sql = "SELECT DATE, DBUSERNAME, GUID, IP, USERNAME, BAN_REASON FROM bans";
//$result = $connection->query($sql);
$sql = "SELECT * FROM bans WHERE";
$types = json_decode($_POST['QUERY_TYPE'], true);
if (in_array("query_admin_username", $types)) {
$sql = $sql . " DBUSERNAME = " . "\"" . $admin_username . "\"" . " &&";
}
if (in_array("query_guid", $types)) {
$sql = $sql . " GUID = " . "\"". $guid . "\"" . " &&";
}
if (in_array("query_ip", $types)) {
$sql = $sql . " IP = " . "\"" . $ip . "\"" . " &&";
}
if (in_array("query_username", $types)) {
$sql = $sql . " USERNAME = " . "\"" . $username . "\"" . " &&";
}
if (in_array("query_ban_reason", $types)) {
$sql = $sql . " BAN_REASON = " . "\"" . $ban_reason . "\"" . " &&";
}
$sql_query = substr($sql, 0, -3);
echo ($sql_query);
$result = $connection->query($sql_query);
while ($connection->query($sql_query)) {
}
if (!$result) {
die("Invalid Query: " . mysqli_error());
}
$row = $result->fetch_array(MYSQLI_NUM);
while ($row = mysqli_fetch_assoc($result)) {
echo ($row);
}
mysqli_close($connection);
?>
As weird as all that looks, it works just how I want it to (I think).
My issue:
I want to be able to get the data from each row and export it as one large String, something along the lines of:
[DATE] DBUSERNAME banned USERNAME (GUID / IP) for BAN_REASON.
I just have absolutely no idea how to go about this. I've tested the Query and it's returning everything it should, however I was using "echo ($row[0])" etc to display them, which is pretty impractical if it's going to return a large amount of rows.
Sorry if something doesn't make sense, my brain is fried at the moment. Please let me know if I forgot anything.
You could concatenate the columns like this if the rest of your script works:
SELECT CONCAT('[',DATE,'] ',DBUSERNAME,' banned ',USERNAME,'(',COALESCE(GUID, IP),),') for ', BAN_REASON) AS your_columns_in_one_line FROM your_table WHERE .....;
See this link for reference to CONCAT
This code works, with one exception. I am importing the dates of performances from a calendar. When the code grabs the next performance date, I want it to read whether it starts before 6PM or after. If before, I want it to say "Today" and if it is after, I want it to say "Tonight." I have tried using $dateEvent("H"), but it says I'm calling a function. How do I convert the date of the event into a variable that I can use?
function calendar_dates() {
$servername = "localhost";
$username = "angelsdb";
$password = "R#start2013";
$dbname = "angelsice";
$fromToday = date("Y-m-d");
/// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT event_start_date, recurrence_interval, event_name, post_content, event_start_time, event_slug, event_all_day FROM wp_em_events";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$fromCalendar = $row["event_start_date"];
$dateEvent = new DateTime($fromCalendar);
$dateToday = new DateTime($fromToday);
if(strtotime($fromToday) <= strtotime($fromCalendar) && $row["recurrence_interval"] < 1){
if($dateToday == $dateEvent) {
/// THIS IS WHERE I WANT TO TEST IF IT IS BEFORE 6PM OR AFTER USING THE VARIABLE $GREETING
$time = new DateTime($row["event_start_time"]);
echo "<h2>" . $greeting . " # " . $time->format('h:i a') . "</h2>";
echo "<a href='../events/". $row['event_slug'] . "'><h1>" . $row["event_name"] . "</h1></a>";
echo "<h3>" . $row["post_content"] . "</h3>";
} else {
$date = $dateEvent;
$time = new DateTime($row["event_start_time"]);
echo "<h2>" . $date->format('l') . " # " . $time->format('h:i a') . "</h2>";
echo "<a href='../events/". $row['event_slug'] . "'><h1>" . $row["event_name"] . "</h1></a>";
echo "<h3>" . $row["post_content"] . "</h3>";
}
return;
}
}
} else {
echo "0 results";
}
mysqli_close($conn);
}
try this
$dateEvent = "2011-07-26 20:05:00";//for example
$dateEvent = strtotime($dateEvent);
$time= date('H', $dateEvent);
if((int)$time>18)
echo 'Tonight';
else
echo 'Today';
ideone
Compare the date to a DateTime at 6pm see the ideone
<?php
// your code goes here
$t1 = new DateTime("4:30pm");
$t2 = new DateTime("8:30pm");
function todayTonight($t) {
return (new DateTime("6:00pm") < $t) ? "Tonight" : "Today";
}
echo todayTonight($t1) . "\n";
echo todayTonight($t2) . "\n";
The below php database query (from phpMyAdmin) only brings back one value (the first one or the oldest) into amcharts:
<?php
class custom_class2
{
var $charts; // reference to the calling object.
function customfunction2($content,$conf)
{
global $TSFE;
$TSFE->set_no_cache();
// do whatever you want here
// db connection
mysql_connect("hostname", "username", "password");
mysql_select_db("database name");
//db abfrage
$query = "
SELECT
YEAR(datetime) AS dy,
MONTH(datetime) -1 AS dm,
DAY(datetime) AS dd,
HOUR(datetime) AS th,
MINUTE(datetime) AS tm,
temp,
hum,
pressure
FROM stock1
ORDER BY datetime
";
// NEW: Variable definition
$zeilenzaehler = 1;
// output of the rows
$result = mysql_query($query) OR die("Error: $query <br>" . mysql_error());
while ($row = mysql_fetch_array($result))
{
// return
if ($zeilenzaehler != 1)
{
$content.= ",";
}
$content.= "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
return $content;
// Variable now on 2
$zeilenzaehler = 2;
}
}
}
?>
Everything else looks like its working fine. Many thanks for the help
You return the first found result in your while-loop. That is why you have just one result. Also as mysql_* functions are depreceted consider switching to
mysqli_* or PDO.
I am adding code from your request:
<?php
class custom_class2
{
var $charts; // reference to the calling object.
function customfunction2($content,$conf)
{
global $TSFE;
$TSFE->set_no_cache();
// do whatever you want here
// db connection
$mysqli = new mysqli("hostname", "username", "password", "database name");
if ($mysqli->connect_error) {
// your error handling here
}
//db abfrage
$query = "
SELECT
YEAR(datetime) AS dy,
MONTH(datetime) -1 AS dm,
DAY(datetime) AS dd,
HOUR(datetime) AS th,
MINUTE(datetime) AS tm,
temp,
hum,
pressure
FROM stock1
ORDER BY datetime
";
// NEW: Variable definition
$zeilenzaehler = 1;
// output of the rows
$result = $mysqli->query($query);
if (FALSE === $result) {
// you can put different error handling here
echo 'Error: ' . $query . ' ' . $mysql->error);
die();
}
$total = array();
while (NULL !== ($row = $result->fetch_array()))
{
// return
if ($zeilenzaehler != 1)
{
$content.= ",";
}
$content.= "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
// return $content;
// if you not return the first result you can gather results in array, so array will contain every row in result, $total[0], $total[1]...:
// $total[] = $content; or:
$total[] = "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
// Variable now on 2
$zeilenzaehler = 2;
}
$result->free();
return $total; // return all rows
}
}
?>