Function declaring two times error - php

I'm trying to understand functions. I created a function and i want to call it multiple times. First I do a SQL query, save it in an array and convert it to seconds. The next thing is do a new SQL query (which does his job perfectly fine). When I try to convert this to seconds it goes wrong, I get this error:
Cannot redeclare myfunction() (previously declared in C:\xampp\htdocs\webpagina met input - kopie\try.php:103) in C:\xampp\htdocs\webpagina met input - kopie\try.php on line 103.
Can anyone help?
<?php
$servername = "localhost"; //inloggegevens database
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
// check of er nog genoeg tijd over is en vergelijk met ingevoerde tijd
$sql1 = "SELECT tijd FROM gespeeldeTijd"; // get data with sql query
sqlquery($sql1, $conn, "tijd");
if ($stateLoop == "1") {
convertArrayToMHS($myArray);
hsmToSeconds($sumUren, $sumMinuten, $sumSeconden);
print_r($seconden);
$myArray = [];
$stateLoop == "0";
$sql2 = "SELECT tijd FROM toegelatentijd WHERE naam = 'thomas'"; // get data with sql query
sqlquery($sql2, $conn, "tijd");
if ($stateLoop == "1") {
convertArrayToMHS($myArray);
hsmToSeconds($sumUren, $sumMinuten, $sumSeconden);
print_r($seconden);
$myArray = [];
$stateLoop == "0";
}
} else {
}
// check of er nog een tijd loopt
$sql1 = "SELECT stopTijd FROM gespeeldeTijd ORDER BY ID DESC LIMIT 1"; // get data with sql query
sqlquery($sql1, $conn, "stopTijd");
if ($stateLoop == "1") {
/* print_r($myArray); */
// get time now an compare these to the time asked in sql 1, if time is still not reached get time and display, if time is reached show input field
} else {
}
}
function sqlquery($sql, $conn, $naamtabel) {
global $myArray;
global $stateLoop;
$stateLoop = "0";
$result = $conn->query($sql);
if ($result->num_rows > 0) { // do a while loop to fetch all data to an array
// output data of each row
while ($row = $result->fetch_assoc()) {
$myArray[] = $row["$naamtabel"]; //alle data van kolom "tijd" in een array
/* print_r($myArray); */
}
$stateLoop = "1";
} else { // if there are no results
echo "0 results";
}
}
function convertArrayToMHS($myArray) {
global $sumUren;
global $sumMinuten;
global $sumSeconden;
global $array_product;
function myfunction($value) { //function to do to evry part of the array
global $array_product;
$array_product[] = explode(":", $value); // split the time in hours, minutes, seconds
return $array_product; //bevat alle gesplitte waardes
}
array_walk($myArray, "myfunction"); // walk trough evry part of the array en voer er "myfunction" op uit
/* print_r($array_product); */
/* print_r($totalElements); */
$uren = array_column($array_product, '0'); // zet alle waarden in een aparte array met 0 (uren)
$minuten = array_column($array_product, '1'); // zet alle waarden in een aparte array met 0 (uren)
$seconden = array_column($array_product, '2'); // zet alle waarden in een aparte array met 0 (uren)
$sumUren = 0;
$sumMinuten = 0;
$sumSeconden = 0;
foreach ($uren as $uren) { //tel alle uren van de sql database bijeen
$sumUren = $sumUren + $uren;
}
foreach ($minuten as $minuten) { //tel alle minuten van de sql database bijeen
$sumMinuten = $sumMinuten + $minuten;
}
foreach ($seconden as $seconden) { //tel alle seconden van de sql database bijeen
$sumSeconden = $sumSeconden + $seconden;
}
}
function hsmToSeconds($sumUren, $sumMinuten, $sumSeconden) {
global $seconden;
$seconden = ($sumUren * 3600) + ($sumMinuten * 60) + $sumSeconden; //uren/minuten/seconden omzetten naar seconden
}
?>

You call to convertArrayToMHS twice, every call you declare myfunction.
Put myFunction outside of convertArrayToMHS.

Related

PHP putting last inserted row into a session

I'm working on a school project, and I'm currently working on a form.
I'm trying to insert the last inserted row from a table in my database into a session, so I can reuse the info when they want to go back to the form to adapt something.
So the data is being inserted into the database, but when I try to put the variable $insertedGegvens into a session, it returns null, and I don't understand why.
I currently have this:
PDO:
public function selectById($id) {
$sql = "SELECT * FROM `gegevens` WHERE `id` = :id";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':id', $id);
$stmt->execute();
}
public function insert($data) {
$errors = $this->validate( $data );
if (empty($errors)) {
$sql = "INSERT INTO `gegevens`
(`naam`, `gemeente`, `postcode`, `adres`,
`huisnr`, `email`, `tel`)
VALUES (:naam, :gemeente, :postcode, :adres,
:huisnr, :email, :tel)";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':naam', $data['naam']);
$stmt->bindValue(':gemeente', $data['gemeente']);
$stmt->bindValue(':postcode', $data['postcode']);
$stmt->bindValue(':adres', $data['adres']);
$stmt->bindValue(':huisnr', $data['huisnr']);
$stmt->bindValue(':email', $data['email']);
$stmt->bindValue(':tel', $data['tel']);
if ($stmt->execute()) {
return $this->selectById($this->pdo->lastInsertId()); //insert returns last row inserted through function selectById
}
}
return false;
}
public function validate( $data ){
$errors = [];
if (!isset($data['naam'])) {
$errors['naam'] = 'Gelieve een naam in te vullen';
}
if (!isset($data['gemeente'])) {
$errors['gemeente'] = 'Gelieve een gemeente in te vullen';
}
if (!isset($data['postcode'])) {
$errors['postcode'] = 'Gelieve een postcode in te vullen';
}
if (empty($data['adres']) ){
$errors['adres'] = 'Gelieve een adres in te vullen';
}
if (empty($data['huisnr']) ){
$errors['huisnr'] = 'Gelieve een huisnummer in te vullen';
}
if (empty($data['email']) ){
$errors['email'] = 'Gelieve een email in te vullen';
}
if (empty($data['tel']) ){
$errors['tel'] = 'Gelieve een telefoonnummer in te vullen';
}
return $errors;
}
if($_POST['action'] == 'toCheckout'){
$insertedGegevens = $this->orderDAO->insert($_POST);
//trying to insert the info it just inserted into a SESSION['user'] so I can reuse this info when user returns to form
$_SESSION['user'] = array();
$_SESSION['user'] = $insertedGegevens;
//$_SESSION['user'] returns null
if (!$insertedGegevens) {
$error = $this->orderDAO->validate($_POST);
$this->set('errors', $error);
}
$_SESSION['user'] = array();
$_SESSION['user'] = $insertedGegevens;
header('Location: index.php?page=checkout');
exit();
}

Json return null

I have the next problem doing a json to read in Andorid
(the credentials are hidden but connection going good in others files)
class reportes
{
var $parametro;
var $conexion;
function __construct(){
$host = "IP"; $DBName = "DbName";
$usuario="user"; $contrasena="pass";
$driver = "DRIVER={iSeries Access ODBC Driver};
SYSTEM=$host;Uid=$usuario;
Pwd=$contrasena;Client_CSet=UTF-8;";
$this->conexion = odbc_connect($driver, $usuario, $contrasena);
}
function consulta($parametro){
$query=
"SELECT OHSNME,OHTOT$,OHREPÑ
FROM MYDB.SANFPRD.FOMHDR
WHERE OHORDÑ= $parametro ";
echo $query."<br><br>";
if ($this->conexion == 0) {echo "Ha fallado la conexion a la BBDD </br>";}
else{
$datos = array();
$result=odbc_exec($this->conexion,$query);
while($row = odbc_fetch_object($result)){
$datos[]= $row;
}
echo json_encode($datos);
}
}//Fin funcion consulta()
}//Fin de la clase
$consultar = new reportes();
$nota_venta = $_REQUEST['parametro'];
$consultar->consulta($nota_venta);
the response JSON that i get is:
SELECT OHSNME,OHTOT$,OHREPÑ FROM DELLORTO.SANFPRD.FOMHDR WHERE OHORDÑ= 366
[{"OHSNME":"E.C. GM. ","OHTOT$":"1861.00",null:" A07"}]
you can see that OHORDÑ is probably the problem with the 'Ñ'
but this table are part a productive database and i can't update
Solution #1, alias the column name to a name without non-ascii characters:
$query=
"SELECT OHSNME,OHTOT$,OHREPÑ AS OHREPN
FROM MYDB.SANFPRD.FOMHDR
WHERE OHORDÑ= $parametro ";
Solution #2, manually serialize using utf8_encode():
$result=odbc_exec($this->conexion,$query);
while($row = odbc_fetch_object($result)){
$_row_fix = array();
foreach ($row as $field => $val) {
$_row_fix[utf8_encode($field)] = utf8_encode($val);
}
$datos[]= $_row_fix;
}

Extract forex data from xlm with php and simplexml_load_file

<?php
$url = "http://rates.fxcm.com/RatesXML";
$xml = simplexml_load_file($url);
print_r($xml);
?>
This script really works and the output is here:
http://sitoxte.com/test%20mercato/array.php
But what I want to do is put this data to MySQL tabs, I need some help because I want to store the data each minute.
So i Try:
json-to-mysql
but I think that array in xml variable is not adeguate.
I want create a for cicle
and create 69 table like this:
table 1 eur/usd
id - Bid - Ask - High - Low - Direction - Last - timestamp
1
2
3
4...
and so on
refresh mode is simple and I do in this way whit javascript:
<script>
setInterval(function () {}, 3000);
var myVar=setInterval(function(){myTimer()},10000);
function myTimer()
{
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
location.reload();
}
</script>
connetion is simple too and is like this:
//Host:
$localhost="******";
//database
$mioblog=*******;
//Nome utente:
$username=********;
//Password:
$password=*******;
// connessione a MySQL con l'estensione MySQLi
$mysqli = new mysqli("$localhost", "$username", "$password", $mioblog);
// verifica dell'avvenuta connessione
if (mysqli_connect_errno()) {
// notifica in caso di errore
echo "Errore in connessione al DBMS: ".mysqli_connect_error();
// interruzione delle esecuzioni i caso di errore
exit();
}
else
{
// notifica in caso di connessione attiva
echo "Connessione avvenuta con successo";
}
This depends on what you're using for your database, but assuming PDO, something like the below. If you need more details then look up a MySQL tutorial, but hopefully this gets you started and shows you how to traverse the XML.
foreach($xml->Rate as $rate) {
$query = "INSERT INTO tblrate (time, symbol, bid) VALUES (NOW(), :symbol, :bid)";
$query = $pdo->prepare($query);
$query->execute(array(
':symbol' => $rate->#attributes['Symbol'],
':bid' => $rate->Bid;
));
}
edit: If you only need one currency, something like this should work
foreach($xml->Rate as $rate) {
if($rate->#attributes['Symbol'] == 'EURUSD') {
$query = "INSERT INTO tblrate (time, bid) VALUES (NOW(), :bid)";
$query = $pdo->prepare($query);
$query->execute(array(
':bid' => $rate->Bid;
));
}
}
My friend Biagio help me to write code:
foreach($xml->children() as $xml_child){
$Symbol = $xml_child['Symbol'];
$Bid = $xml_child->Bid;
$Ask = $xml_child->Ask;
$High = $xml_child->High;
$Low = $xml_child->Low;
$Direction = $xml_child->Direction;
$Last = $xml_child->Last;
echo('$Symbol = '.$Symbol.'<br>');
echo('$Bid = '.$Bid.'<br>');
}
final code of php scrip that write in mysql tables every second forex data:
...
<body id="top">
<!-- <button onclick="myFunction()">Reload page</button> -->
<a id=demo> <a>
...
<?php
echo date("F j, Y, g:i a", time()).'<br>';
$html="";
$url = "http://rates.fxcm.com/RatesXML";
$xml = simplexml_load_file($url);
//Host:
//echo('var_dump( $xml)<br>');
//var_dump( $xml);
//SimpleXMLElement
//Host:
$localhost="----";
//database
$mioblog=----;
//Nome utente:
$username=-----;
//Password:
$password=-----;
// connessione a MySQL con l'estensione MySQLi
$mysqli = new mysqli("$localhost", "$username", "$password", $mioblog);
// verifica dell'avvenuta connessione
if (mysqli_connect_errno()) {
// notifica in caso di errore
echo "Errore in connessione al DBMS: ".mysqli_connect_error();
// interruzione delle esecuzioni i caso di errore
exit();
}
else {
// notifica in caso di connessione attiva
// echo "Connessione avvenuta con successo";
}
// sql to create table
// sql to create table
foreach($xml->children() as $xml_child){
$Symbol = $xml_child['Symbol'];
$Bid = $xml_child->Bid;
$Ask = $xml_child->Ask;
$High = $xml_child->High;
$Low = $xml_child->Low;
$Direction = $xml_child->Direction;
$Last = $xml_child->Last;
// sql to create table
/*
$sql = "CREATE TABLE $Symbol (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Bid VARCHAR(30) NOT NULL,
Ask VARCHAR(30) NOT NULL,
High VARCHAR(30) NOT NULL,
Low VARCHAR(30) NOT NULL,
Direction VARCHAR(30),
Last VARCHAR(30) NOT NULL,
reg_date TIMESTAMP
)";*/
$sql = "INSERT INTO $Symbol (Bid,Ask,High,Low,Direction,Last)
VALUES ('$Bid','$Ask',$High,$Low,$Direction,'$Last')";
if ($mysqli->query($sql) === TRUE) {
// echo "Inserito in table ".$Symbol." / bid=".$Bid." / ask=".$Ask."/ High=".$High."/ Low=".$Low."/ Direction=".$Direction."/ Last=".$Last."<br>";
} else {
echo "Error creating table: " . $mysqli->error;
}
// echo('$Symbol = '.$Symbol.'<br>');
//echo('$Bid = '.$Bid.'<br>');
//echo('$Ask = '.$Ask.'<br>');
//echo('$High = '.$High.'<br>');
//echo('$Low = '.$Low.'<br>');
// echo('$Direction = '.$Direction.'<br>');
// echo('$Last = '.$Last.'<br>');
}
$mysqli-->close();
?>
....

Loop though database with foreach

I want to browse data from my postgre database with a "foreach". So I made my request like that :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT id_traitement FROM public.traitement WHERE id_essai='.$id_essai.';";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$data = pg_fetch_all($res);
And I get my values with "pg_fetch_all".
After that, I'm looking for compare the data in my database (get with the request) and the data in my web page. So I created this loop :
foreach($array as $ligne_web)
{
foreach($data['id_traitement'] as $ligne_base)
{
if(($ligne_web[0] == $ligne_base) and ($flag))
{
//update de la ligne
update_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
$flag2 = false;
break 1;
}
}
if(($flag) and ($flag2))
{
insert_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
}
}
When I try to run it, firebug tells me : Invalid argument supplied for foreach(). So I don't know how to browse the rows in the database. Certainly my problem is in my foreach, but I don't find what's wrong.
Help please !
It seems your second foreach needs to be '$data' instead of $data['id_traitement']
So your code need to changed to ,
foreach($arr as $ligne_web)
{
foreach($data as $ligne_base) // <-- Here is the correction
{
if(($ligne_web[0] == $ligne_base) and ($flag))
{
------ REST of your Codes ------
Ok, I found an answer. Instead of an array $data from my database, and directly after the request, I created a new array.
Here is my code :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT id_traitement FROM public.traitement WHERE id_essai='.$id_essai.';";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$tableau_database_final = array();
while ($data = pg_fetch_all($res)) //Here is my array
{
$tableau_database = array('id_traitement'=>$data['id_traitement']);
array_push($tableau_database_final,$tableau_database);
}
$flag2 = true;
foreach($array as $ligne_web)
{
foreach($tableau_database_final as $ligne_base)
{
echo ($ligne_web[0]);
echo ($ligne_base);
if(($ligne_web[0] == $ligne_base)) //Si il existe une ligne ayant déjà le même id traitement
{
//update de la ligne
update_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
$flag2 = false;
break 1;
}
}
if(($flag) && ($flag2))
{
//insert_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
}
}

runnun multiple functions on webpage

I have an webpage on which i want to display 2 separate tables with content from the same database. How do i run separate functions on a webpage and display 2 different results?
The code i have so far:
the second query that i want to run is in it as query2, but this doesn`t work....
<?php
$server = "localhost";
$user = "776";
$wachtwoord = "776";
$database = "kse001_h5mh";
$query = "SELECT beschrijving FROM supermarkt WHERE soort = 'komkommertest'"; //de SQL-query
$resultaat = ""; // hierin wordt het resultaat van de query opgeslagen
if (!$db = mysql_connect($server, $user, $wachtwoord)){ // probeert de verbinding te maken
$melding = "<h2>Verbinding maken met databaseserver is mislukt!</h2>";
}
else{
$melding = "<h2>Verbinding maken met databaseserver is tot stand gebracht!</h2>";
if(!mysql_select_db($database)){ // open de gewenste database
$melding .= "...maar de database \"$database\" kon niet worden gevonden!";
} else {
$melding .= "en de database \"$database\" is geselecteerd!";
if(!$resultaat = mysql_query($query, $db)){
$melding .= "<br />...maar de query \"$query\" kon niet worden uitgevoerd!";
} else {
$melding .="<br />De query \"$query\" is met succes uitgevoerd!";
}
}
$query2 = "SELECT beschrijving FROM supermarkt WHERE soort = 'hamburger'"; //de SQL-query
$resultaat2 = ""; // hierin wordt het resultaat van de query opgeslagen
if (!$db = mysql_connect($server, $user, $wachtwoord)){ // probeert de verbinding te maken
$melding = "<h2>Verbinding maken met databaseserver is mislukt!</h2>";
} else {
$melding = "<h2>Verbinding maken met databaseserver is tot stand gebracht!</h2>";
if(!mysql_select_db($database)){ // open de gewenste database
$melding .= "...maar de database \"$database\" kon niet worden gevonden!";
} else {
$melding .= "en de database \"$database\" is geselecteerd!";
if(!$resultaat2 = mysql_query($query, $db)){
$melding .= "<br />...maar de query \"$query\" kon niet worden uitgevoerd!";
} else {
$melding .="<br />De query \"$query\" is met succes uitgevoerd!";
}
}
mysql_close($db); //database afsluiten
?>
</head>
<body>
<?php echo $melding; ?>
<hr />
<?php
while(list($bescrijving) = mysql_fetch_row($resultaat))
{
echo "$bescrijving is geboren op <br />";
}
?>
<?php
while(list($bescrijving) = mysql_fetch_row($resultaat2))
{
echo "$bescrijving is geboren op <br />";
}
?>
</body>
First problem, stop using mysql_ functions family... this kind of function was deprecated and will stop work soon or just don't run appropriately.
You should change to PDO family functions try this:
$dbh = new PDO('mysql:host=localhost;dbname=kse001_h5mh', '776', '776');
$query1 = $dbh->query("SELECT beschrijving FROM supermarkt WHERE soort = 'komkommertest'");
$query1->fetchAll(); // bring the result
$query2 = $dbh->query("SELECT beschrijving FROM supermarkt WHERE soort = 'hamburger'");
$query2->fetchAll(); // bring the result
This should work.
You can run 2 process of your script using the pcntl-fork function.
You can also try to use ob_flush function to send the output buffer between your 2 database requests.
In your case, I think it's a better option to load data in AJAX if it's possible.

Categories