I have an array that looks like:
Array ( [0] => 'overview'
[53] => 'PUBLIC'
[54] => '-friendsD'
[55] => 'XHTML'
[56] => '1.0'
[57] => 'Transitional'
[77] => 'People' );
How can I take those values and put them into MySQL with an INSERT? For example INSERT INTO array_value VALUES ('$arrayvalues'). For each array value is a new post into MySQL.
I tried this:
<?php
$homepage = file_get_contents('http://www.mysiteexample.com/');
$array = explode(" ",$homepage);
foreach($array as $val) {
$servername = "localhost";
$username = "111";
$password = "111";
$dbname = "111";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
if ($val != " "){
$val = $val. " ";
$query = "INSERT INTO `111` (word) VALUES ('$val')";
$executeQuery = $conn->query($query) === TRUE;
}
if ($executeQuery === TRUE) {
//echo "New record created successfully";
echo $val;
} else {
//echo "Error: " . $query . "<br>" . $conn->error;
echo $val. " ";
}}
$conn->close();
}
?>
This works to some extent. It produces many empty results how could it be filtered to have no empty posts. I tried the $val != " " but this didnt work.
You can loop through the array and build the query. Then execute it.
<?php
$homepage = file_get_contents('http://www.mywebsite.com/');
$array = explode(" ",$homepage);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
$executeQuery;
for ($i = 0; $i < count($array); $i++) {
if (!empty($array[$i])) {
$executeQuery = $conn->query("INSERT INTO `yourTable` (yourField) VALUES ('" . $array[$i] . "')");
}
}
if ($executeQuery === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
$conn->close();
}
?>
Related
I want to set up a website with a form in it. The form will transfer the data to the DB, but I think it is not safe to let the personal data in the DB which is external reachable.
So I thought I should transfer the data via PHP from the DB1(server1 - external reachable) to DB2(server2 - only internal reachable).
The following picture should help to know what I am searching for.
Is there any names/methods to google for?
From php you just have to create a new connection for DB2.
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
$servername2 = "localhost";
$username2 = "database2";
$password2 = "xxxxxxxx";
$dbname2 = "database2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn2 = new mysqli($servername2, $username2, $password2, $dbname2);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
if ($conn2->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn2->error;
}
$conn->close();
$conn2->close();
?>
I`m new to PHP and coding in general. How can I echo out the number 27600 from the code below using PHP? The array was generated with Query:
SELECT sum(amount) FROM foo
Array ( [0] => stdClass Object ( [sum(amount)] => 27600 ) )
with single echo from MySQL OOP.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT sum(amount) AS total FROM foo";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "My Total: " . $row["total"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
So I am trying to get conversion rates from an API and I get the following data:
https://api.exchangeratesapi.io/history?start_at=2017-01-01&end_at=2018-09-01&symbols=EUR&base=GBP
How can I loop over the data and insert date & conversion rate into MYSQL DB.
Any help is greatly appreciated.
I am currently standing here:
$host="localhost";
$user="conversion";
$pass="password";
$db="areporting";
$connect= new mysqli($host,$user,$pass,$db) or die("ERROR:could not connect
to the database!!!");
$string = file_get_contents("https://api.exchangeratesapi.io/history?start_at=2017-01-01&end_at=2018-09-01&symbols=EUR&base=GBP");
$json = json_decode($string, true);
var_dump($json);
here a screenshot of the Data I get:
You can use foreach on json result :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$string = file_get_contents("https://api.exchangeratesapi.io/history?start_at=2017-01-01&end_at=2018-09-01&symbols=EUR&base=GBP");
$json = json_decode($string, true);
foreach($json['rates'] as $date =>$conversion){
$sql = "INSERT INTO Mytable (id, date, conversion)
VALUES ( '$date', ".$conversion['EUR'].")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully"."<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."<br>";
}
}
$conn->close();
?>
Thanks for all the Tips, here I have my working solution:
foreach($json['rates'] as $date => $conversion){
$timestamp = strtotime($date);
$sql = "INSERT INTO m_fx_rate_temp
(`base`, `counter`, `fxRate`, `date`) VALUES ('gbp', 'eur', ".$conversion['EUR'].", Date_format(FROM_UNIXTIME($timestamp), '%Y-%m-%d'))";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully"."<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."<br>";
}
}
I am trying to select a column in mysql in php,
function PageController() {
$data = [
'categories' => _db_get_select("categories", ['name'])
];
load_view("tutu", $data);
and
function _db_get_select($table_name, $columns) {
$servername = _c("database.server_name");
$username = _c("database.username");
$password = _c("database.password");
$dbname = _c("database.db_name");
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$sql = "SELECT name=$columns FROM . $table_name.";
var_dump($sql);
the result is displaying like this
string(42) "SELECT ['name']=Array FROM . categories."
I want to be like this
SELECT name FROM . categories.
Thanks in advance.
You may use this script
function PageController() {
$data = [
'categories' => _db_get_select("categories", "name")
];
load_view("tutu", $data);
And the function will be
function _db_get_select($table_name, $columns) {
$servername = _c("database.server_name");
$username = _c("database.username");
$password = _c("database.password");
$dbname = _c("database.db_name");
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT {$columns} FROM {$table_name}";
}
Just echo your sql variable instead of var dump like below
echo $sql;
Use foreach loop to iterate through an array of columns to form a query.
function PageController() {
$data = array('categories' => _db_get_select("categories", array("name")));
load_view("tutu", $data);
}
And then:
//Start with select
$sql = 'SELECT ';
//Concat column names separated with commas
foreach ($columns as $value) {
$sql .= $value . ', ';
}
//Get rid of the last comma
$sql = rtrim($sql, ', ');
$sql .= ' FROM ' . $table_name;
Check if it's okey:
var_dump($sql);
I need some help finding my error on the enclosed code. When I run either of the two queries using the if ($conn->query($sql) === TRUE) { method each works correctly. But when I try to combine them with the if ($conn->multi_query($sql) === TRUE) { method. No records are uploaded. What am I doing wrong here.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection made...";
$payload_dump = $_POST['payload'];
echo $payload_dump;
$payload_array = json_decode($payload_dump,true);
if(is_array($payload_array)){
foreach($payload_array as $row){
//get the data_payload details
$device = $row['device'];
$type = $row['data_type'];
$zone = $row['zone'];
$sample = $row['sample'];
$count = $row['count'];
$time = $row['date_time'];
$epoch = $row['epoch_stamp'];
$sql = "INSERT INTO data(device, type, zone, sample, count, date_time, epoch_stamp) VALUES('$device', '$type', '$zone', '$sample', '$count', '$time', '$epoch');";
$sql . = "UPDATE data SET date_time = FROM_UNIXTIME(epoch_stamp);";
if ($conn->multi_query($sql) === TRUE) {
//if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
... and yes I realize this code is not secure but it's ok for my testing purposes.
Intrinsically the code below is the same until we get to the loop where we build up an array of queries to be executed and execute the multi_query() once at the end once we leave the loop. I have removed some of the comments and statements that echo out info at the start for brevity. I hope this looks ok and works....
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname);
if( $conn->connect_error ) die("Connection failed: " . $conn->connect_error);
$payload_dump = $_POST['payload'];
$payload_array = json_decode($payload_dump,true);
if( is_array( $payload_array ) ){
$queries=array();
foreach( $payload_array as $row ){
//get the data_payload details
$device = $row['device'];
$type = $row['data_type'];
$zone = $row['zone'];
$sample = $row['sample'];
$count = $row['count'];
$time = $row['date_time'];
$epoch = $row['epoch_stamp'];
/*note: we do not need to add the semi-colon here as it gets added later when we implode the array */
$queries[]="INSERT INTO `data` ( `device`, `type`, `zone`, `sample`, `count`, `date_time`, `epoch_stamp` ) VALUES ('$device', '$type', '$zone', '$sample', '$count', '$time', '$epoch')";
}
/*
Previously the below query was being execute on every iteration
~ because $epoch is now the last one encountered in the array,
the value that is updated in ALL records is as it would have been
previously.
*/
$queries[]="UPDATE `data` SET `date_time` = from_unixtime( $epoch );";
$sql=implode( ';', $queries );
if ( $conn->multi_query( $sql ) === TRUE ) {
echo "New records created and updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>