How do I need to adjust the below php if the output of the php-script needs to be saved in $content?
<?php
//db verbindung
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 wettertabelle
WHERE DATE(datetime) = '2013-11-25'
ORDER BY datetime
";
// NEU: Variable definieren
$zeilenzaehler = 1;
//ausgabe der zeilen
$result = mysql_query($query)
OR die("Error: $query <br>" . mysql_error());
while ($row = mysql_fetch_array($result)) {
// echo
if ($zeilenzaehler != 1) {
echo ",";
}
echo "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
//Variable jetzt auf 2
$zeilenzaehler = 2;
};
?>
What is working is e.g.:
<?php
$content = This is the output!!
?>
or
<?php
ob_start();
echo 'This is the output!!';
$content=ob_get_contents();
ob_end_clean();
?>
How would I need to adjust the above script to get it into the following output structure:
<?php
class user_klasse
{
function ausgabe()
{
return 'This test is generated by php.';
}
}
?>
You only have two echo statements, change them to save the value in your variable. No need for output buffering for something so small.
if ($zeilenzaehler != 1)
{
$content.= ","; // instead of echo, and same for the one below
}
$content.= "{date: new Date(".$row['dy'].",".$row['dm'].",".$row['dd'].",".$row['th'].",".$row ['tm']."),t:".$row['temp'].",h:".$row['hum'].",p:".$row['pressure']."}";
At the end you can just do
echo $content;
Related
I have this code and in "SELECT * FROM Blogi WHERE PostID=".
How to get each line separately so that takes postedBY, title, date, content by PostID
<?php
try{
$Blog = $conn->prepare("SELECT * FROM Blogi WHERE PostID=");
$Blog->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
$fetch = $Blog->fetchAll();
$usercount = $Blog->rowCount();
if($usercount > 0){
foreach($fetch as $f){
$PostID = $f['PostID'];
$PostedBY = $f['PostedBY'];
$Title = $f['Title'];
$Date = $f['Date'];
$Content = $f['Content'];
}
}else{
session_destroy();
header('location: index.php');
}
?>
I have very bad English, so I don't know anyone can understand this.
How to do it further this postID="" to that he would start to work?
You have already done it in foreach loop... so add a line for output like... Also you aren't sending any PostID value to your query, be sure that you are sending a value for it.
foreach($fetch as $f){
$PostID = $f['PostID'];
$PostedBY = $f['PostedBY']
$Title = $f['Title'];
$Date = $f['Date'];
$Content = $f['Content'];
echo $PostID . " " . $Title . " " . $Date . " " . $Content . "<br />";
}
Good day,
I'm trying to run a stored procedure on a mysql server by calling a php function.
I have used a lot of 'echo' lines to check where the problem could be but it seems that the problem occurs at the very end of my process when I try to send the data (namely '$idComponent' and '$data_get'). However, even if I set fixed values (50 for the id component and 50 for the value), the stored procedure does not send data to my table, either.
Before annoying you, I have been googling for a while, but now I am quite lost as I don't really know now where to look at.
<?php
/*
php_update_survey_local.php
*****************************************************************************************
* This script updates the value of the components in the table tbl_domotique_components
* It calls the stored procedure 'sp_tbl_eedomus_local_surveys_insert'
*****************************************************************************************
Version 1.00, 08.06.2017, Initial version of the script
*/
mainProcess();
function mainProcess()
{
$stringLen = 0;
$stringValue1 = "";
$stringValue2 = "";
$mavalue = "vide";
$data_get = -9999.999;
$eedomus_api_link = "https://api.eedomus.com/get?api_user=user&api_secret=data&action=periph.caract&periph_id=";
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo "Link : " . $actual_link . "<br>" ;
$stringLen = strlen($actual_link);
echo "Length : " . $stringLen;
$stringPos1 = strpos($actual_link, 'Param1');
$stringPos2 = strpos($actual_link, '&', $stringPos1);
$stringValue1 = substr($actual_link, $stringPos1+7, $stringPos2 - $stringPos1 - 7);
echo "Pos : " . $stringPos2;
echo "Extracted string 1 : #" . $stringValue1 . "#<br>";
$stringPos1 = strpos($actual_link, 'Param2', $stringPos2);
$stringValue2 = substr($actual_link, $stringPos1+7, $stringLen - $stringPos1 - 7);
echo "Pos : " . $stringPos1;
echo "Extracted string 2 : #" . $stringValue2 . "#<br>";
$ServerIP = "myIPAddress";
$sqlUser = "domoos";
$sqlDatabase = "domoos_test_db";
$pw = "toto";
$file_input_1 = "../auto/file/update_data_" . $stringValue1. ".txt" ;
$eedomus_component_path_full_1 = $eedomus_api_link . $stringValue1;
getFile($file_input_1, $eedomus_component_path_full_1);
$data_get = extractData($file_input_1, $eedomus_component_path_full_1);
// Connect
$mysqli = new mysqli($ServerIP, $sqlUser, $pw, $sqlDatabase);
if(!$mysqli) {
header('Location: error.php?error=DbConnectionFailure');
die();
}
$idComponent = intval($stringValue1);
echo "ID COMP = " . $idComponent;
echo "VALUE = " . $data_get;
// Prepare IN parameters
// $mysqli->query("SET #p_Id_Component = '" . $idComponent . "'");
// $mysqli->query("SET #p_Value = '" . $data_get . "'");
$mysqli->query("SET #p_Id_Component = 50");
$mysqli->query("SET #p_Value = 50");
if(!$mysqli->query("CALL sp_tbl_eedomus_local_surveys_insert (#p_Id_Component, #p_Value)"))
{
echo "OK";
if($mysqli) $mysqli->close(); // Close DB connection
//header('Location: error.php?error=QueryFailure');
die();
}
if($mysqli) $mysqli->close(); // Close DB connection
}
function getFile($file_input, $eedomus_component_path_full_1)
{
file_put_contents($file_input, fopen($eedomus_component_path_full_1, 'r'));
sleep(1);
}
function extractData($file_input, $eedomus_component_path_full_1)
{
// Fonction pour mettre à jour la température dans domoos
if ( 0 == filesize( $file_input ) )
{
// file is empty - the treatment is stopped here
// writeToLog($log_file_name, "[Failure] Empty file detected (" . $file_input . ")");
}
else
{
echo "fichier PAS vide";
$consolidated = "";
$lines = file($file_input);
// writeToLog($log_file_name, "[Success] Eedomus component data collected (" . $eedomus_component_path_full_1 . " -> " . $file_input . ")");
foreach($lines as $line)
{
$consolidated = $consolidated . $line;
}
// Initial values
$Temperature_Float = 0;
$Pos1 = 0;
$Pos2 = 0;
$Pos3 = 0;
$Pos4 = 0;
$Json_Input = $consolidated;
$Pos1 = strpos($Json_Input, "\"last_value\"", 0);
$Pos2 = strpos($Json_Input, ":", $Pos1+1);
$Pos3 = strpos($Json_Input, "\"", $Pos2+1);
$Pos4 = strpos($Json_Input, "\"", $Pos3+1);
$Temperature_String = substr($Json_Input, $Pos3+1, $Pos4-$Pos3-1);
$Temperature_Float = floatval($Temperature_String);
echo "Coucou. " . "A la maison, il fait maintenant : <b>" . round($Temperature_Float,0) . "°C</b>";
echo "<br>Contrôle : ";
echo "<br>Position 1 : " . $Pos1;
echo "<br>Position 2 : " . $Pos2;
echo "<br>Position 3 : " . $Pos3;
echo "<br>Position 4 : " . $Pos4;
echo "<br>Chaîne extraîte : " . $Temperature_String;
// return round($Temperature_Float,0);
return $Temperature_Float;
}
}
?>
If it's useful here is what my stored procedure 'sp_tbl_eedomus_local_surveys_insert' does :
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_tbl_eedomus_local_surveys_insert`(IN `p_Id_Component` INT, IN `p_Value` FLOAT, OUT `p_last_id` INT)
NO SQL
BEGIN
INSERT INTO tbl_eedomus_local_surveys
(
eedomus_id,
eedomus_value
)
VALUES
(
p_Id_Component,
p_Value
);
SET
p_last_id = LAST_INSERT_ID();
END$$
DELIMITER ;
Any idea of what am I doing wrong here? Many thanks for your time and for reading me.
I'm trying to query some vars in my MySQL db, but for some reasons it returns 0.
Here's the code:
<html>
<body>
<?php
session_start();
$connection = mysqli_connect("", "", "", "");
if (empty($connection))
$error = "Could not connect to Database, please contact an admin with this code: DBE1";
$tnews = mysqli_query($connection, "SELECT * FROM Test ORDER BY ID DESC");
while ($news = mysqli_fetch_array($tnews))
{
$title = $news['Title'];
$pimg = $news['PrevImg'];
$ptext = $news['PrevText'];
$text = $news['Text'];
$img1 = $news['Img1'];
echo "<h1>" + $title + "</h1><br><br>";
echo "<p>" + $pimg + "</p>";
echo "<br><p>" + $ptext + "</p><br><br>";
echo "<p>" + $text + "</p>";
echo "<br><p>" + $img1 + "</p>";
echo $title;
}
mysqli_close($connection);
?>
</body>
</html>
Oh and the result
00000
I have another site where almost (var names, echo's, ...) everything is the same, it works there! I have really have no idea what's wrong, does anyone have an idea?
P.S: The DB Connection has empty strings because it has the ip, username, password and db of my database! ;D
Thanks for the help!
The + is a concatenate operator in JS, use PHP's equivalent, being a dot .
Now, as stated in comments, you are outputting content before sessions.
You may get a warning similar to this:
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /path/to/file:3) in /path/to/file.php on line 4
Corrected code, is you still want to use sessions. If not, just remove session_start();
Sidenote: It is important not to have a space before <?php or any other output such as HTML, a cookie or a byte order mark, which will also account as outputting before header.
<?php
session_start();
?>
<html>
<body>
<?php
$connection = mysqli_connect("", "", "", "");
if (empty($connection))
$error = "Could not connect to Database, please contact an admin with this code: DBE1";
$tnews = mysqli_query($connection, "SELECT * FROM Test ORDER BY ID DESC");
while ($news = mysqli_fetch_array($tnews))
{
$title = $news['Title'];
$pimg = $news['PrevImg'];
$ptext = $news['PrevText'];
$text = $news['Text'];
$img1 = $news['Img1'];
echo "<h1>" . $title . "</h1><br><br>";
echo "<p>" . $pimg . "</p>";
echo "<br><p>" . $ptext . "</p><br><br>";
echo "<p>" . $text . "</p>";
echo "<br><p>" . $img1 . "</p>";
echo $title;
}
mysqli_close($connection);
?>
</body>
</html>
Add error reporting to the top of your file(s) which will signal warnings/errors as shown further up in my answer.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
I don't know how that worked out in your other server, but you should be using dots . instead of + to concatenate strings in php.
while ($news = mysqli_fetch_array($tnews))
{
$title = $news['Title'];
$pimg = $news['PrevImg'];
$ptext = $news['PrevText'];
$text = $news['Text'];
$img1 = $news['Img1'];
echo "<h1>" . $title . "</h1><br><br>";
echo "<p>" . $pimg . "</p>";
echo "<br><p>" . $ptext . "</p><br><br>";
echo "<p>" . $text . "</p>";
echo "<br><p>" . $img1 . "</p>";
echo $title;
}
I need to migrate data within our old bug tracker (Zentrack) to our new one and the only import method I can use is to import from CSV. To do so I need the data from two tables, tickets and logs so I wrote the script below in php.
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "dbuser";
$pass = "dbpass";
$db = "zentrk";
$users[1] = 'john';
$users[4] = 'sally';
$users[5] = 'nick';
$users[6] = 'ralph';
$r = mysql_connect($host, $user, $pass);
if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
echo mysql_get_server_info() . "\n";
$r2 = mysql_select_db($db);
if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
$query_tickets = "select ZENTRACK_TICKETS.id, ZENTRACK_TICKETS.title, ZENTRACK_TICKETS.priority, ZENTRACK_TICKETS.status, ZENTRACK_TICKETS.description, ZENTRACK_TICKETS.otime,
ZENTRACK_TICKETS.type_id, ZENTRACK_TICKETS.user_id, ZENTRACK_TICKETS.system_id, ZENTRACK_TICKETS.creator_id, ZENTRACK_TICKETS.proj_key
from ZENTRACK_TICKETS
where ZENTRACK_TICKETS.status = 'OPEN'
and ZENTRACK_TICKETS.system_id in ('18', '3', '6', '1', '16', '7', '9', '4', '20')
and ZENTRACK_TICKETS.type_id not in ('1', '10', '5')";
$rs = mysql_query($query_tickets);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}
$export = array();
$export[] = 'id,title,created date,priority,type,assigned,description,system,creator,project key,log1,log2,log3,log4,log5,log6,log7,log8,log9,log10
';
while ($row = mysql_fetch_assoc($rs)) {
$line = '';
$count = 0;
$line .= $row['id'] . "," . $row['title'] . "," . date('d-M-y h:m a',$row['otime']) . "," . $row['priority'] . "," . $row['type_id'] . "," . $row['user_id'] . "," . $row['description'] . "," . $row['system_id'] . "," . $row['creator_id'] . "," . $row['proj_key'] . ",";
$logs = find_logs($id = $row['id']);
foreach($logs as $log_entry) {
$line .= $log_entry.",";
$count++;
}
while($count < 10) {
$line .= ",";
$count++;
}
$export[] = $line.'
';
}
mysql_close();
// print_r($export);
$file = 'tickets.csv';
file_put_contents($file, $export);
function find_logs($ticket) {
$content = array();
$query = "select ZENTRACK_LOGS.created, ZENTRACK_LOGS.user_id, ZENTRACK_LOGS.entry
from ZENTRACK_LOGS
where ZENTRACK_LOGS.ticket_id = $ticket
and ZENTRACK_LOGS.action <> 'EDIT' ";
$rs = mysql_query($query);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
}
while ($row = mysql_fetch_assoc($rs)) {
$date = date('d-M-y h:m a',$row['created']);
$content[] = $date . ";" . $row['user_id'] . ";" . $row['entry'];
}
return $content;
}
?>
I'm running into two problems with this script, that I'm sure are due to me being new to PHP.
1) I need to escape out the data in $row['description'] as it contains both carriage returns and , in the text that is incorrectly breaking the output into new rows when saved to CSV. I need to save the contents of this row within " " but I'm not sure how to do so.
2) The data returned in $row['user_id'], $row['creator_id'] and $row['user_id'] within the find_logs function returns a number, which I need to find that number and replace with the corresponding string in the $users array. What's the best way to do this?
When dealing with csv files use fgetcsv and fputcsv, provide it with an array and it will handle the escaping for you.
i Have This PHP and JS Code on my web page.
<?php
include 'connect1.php';
$query = "SELECT URL FROM remontee_nlf ORDER BY URL ASC";
$result = mysql_query($query) or die (mysql_error());;
$counter = 0;
// write the values from the database into the javascript array
echo "<script type='text/javascript'>";
echo "this.styleListArray = new Array();";
if ($result) {
while($row = mysql_fetch_array($result)) {
echo("this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';"); // displays 'lname, fname'
$counter += 1;
}
}
echo("</script>");
?>
The Problem is that when i execute the page containing the code, a part of this code doesn't get executed and it just shows on the page as a simple text :
"); echo "this.styleListArray = new Array();"; if ($result) { while($row = mysql_fetch_array($result)) { echo("this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';"); // displays 'lname, fname' $counter += 1; } } echo(""); ?>
I tried to figure it out, but i couldn't get it, if you can help brothers, that would be wonderful.
Try rewriting your code like this:
include 'connect1.php';
$query = "SELECT URL FROM remontee_nlf ORDER BY URL ASC";
$result = mysql_query($query) or die (mysql_error());
$counter = 0;
// write the values from the database into the javascript array
echo <<<HTML
<script type='text/javascript'>
this.styleListArray = new Array();
HTML;
$strLine = '';
if ($result) {
while($row = mysql_fetch_array($result)) {
$strLine.= "this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';";
$counter += 1;
}
}
echo $strLine;
echo("</script>");
First of all change your queries to use mysqli or pdo connections
secondly try following code
$sql = 'SELECT URL FROM remontee_nlf ORDER BY URL ASC';
$res = mysql_query($sql, $con);
$rows = array();
while ($row = mysql_fetch_assoc($res))
$rows[] = $row['URL'];
$str = implode('", "', $rows);
$data = '["'.trim($str).'"]';
echo '<script type="text/javascript">';
echo "var data = $data;";
echo 'console.log(data)';
echo '</script>';
check you console log.
You have $result = mysql_query($query) or die (mysql_error());; change it to
$result = mysql_query($query) or die (mysql_error());
Also make sure $row['URL'] and $row['user_fname'] are available.