Insert array into db table - php

I'm trying to learn how to use an array to insert multiple entries into a database table. This was my attempt. What am I doing wrong?
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "hosts";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$client = array(
"1" => array("Jerry Garcia", "193.169.5.11"),
"2" => array("Bill Graham", "193.169.5.12"),
"3" => array("Arlo Guthrie", "193.169.5.13")
);
if(is_array($client) {
$DataArr = array();
foreach($client as $row) {
$fieldVal1 = mysqli_real_escape_string($client[$row][1]);
$fieldVal2 = mysqli_real_escape_string($client[$row][2]);
$fieldVal3 = mysqli_real_escape_string($client[$row][3]);
$DataArr[] = "('fieldVal1', 'fieldVal2', 'fieldVal3')";
}
$sql = "INSERT INTO ip_data (field1, field2, field3) values ";
$sql .= implode(',' , $DataArr);
mysqli_query($conn, $query);
}
I tried this but it still doesn't work. What am I missing?
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "hosts";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$client = array(
"0" => array("Jerry Garcia"),
"1" => array(""193.169.5.11"),
);
if(is_array($client)) {
$DataArr = array();
foreach($client as $row) {
$fieldVal1 = mysqli_real_escape_string($client[$row][0]);
$fieldVal2 = mysqli_real_escape_string($client[$row][1]);
$DataArr[] = "('$fieldVal1', '$fieldVal2')";
}
$sql = "INSERT INTO ip_data (field1, field2) values ";
$sql .= implode(',' , $DataArr);
mysqli_query($conn, $query);
}
Thanks for your advice.
Next try.
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "hosts";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$client = array(
"0" => array("name" => "Peter Maxx", "ip" => "193.169.5.16"),
"1" => array("name" => "Ravi Shankar", "ip" => "193.169.5.17")
);
if(is_array($client)) {
$DataArr = array();
foreach($client as $row) {
$DataArr[] = "('". mysqli_real_escape_string($conn, $row[0]) ."', '". mysqli_real_escape_string($conn, $row[1]) ."')";
}
$sql = "INSERT INTO ip_data (name, ip)
VALUES
( 'Peter Maxx', '193.169.5.16'),
('Ravi Shankar', '193.169.5.17')";
$sql .= implode(", " , $DataArr);
mysqli_query($conn, $sql);
}
I get these error messages.
PHP Notice: Undefined offset: 0 in php shell code on line 5
PHP Notice: Undefined offset: 1 in php shell code on line 5
PHP Notice: Undefined offset: 0 in php shell code on line 5
PHP Notice: Undefined offset: 1 in php shell code on line 5

It is unclear what your purpose is since the SQL-query in your question specify 3 fields (field1, field2, field3) to be inserted into your table, but you only have 2 values in your clients array. If you want to insert multiple rows in one single query, lets say for the "name" and "ip" value in your clients array, you can do this:
if(is_array($client)) {
$DataArr = array();
foreach($client as $row) {
//CREATE ARRAY WITH name AND ip VALUES FOR EACH USER...
$DataArr[] = "('". mysqli_real_escape_string($conn, $row[0]) ."', '". mysqli_real_escape_string($conn, $row[1]) ."')";
}
$sql = "INSERT INTO ip_data (name, ip) VALUES ";
$sql .= implode(", " , $DataArr);
mysqli_query($conn, $sql);
}
The $sql variable will contain the following query compliant with the syntax for a multiple insert:
INSERT INTO ip_data (name, ip)
VALUES ('Jerry Garcia', '193.169.5.11'),
('Bill Graham', '193.169.5.12'),
('Arlo Guthrie', '193.169.5.13')
Note that you have $query instead of $slqin your question. It should be: mysqli_query($conn, $sql);.
Another thing: Using mysqli_real_escape_string() the procedural way instead of the object oriented way, as in your example, requires to pass a link identifier to the connection as parameter: mysqli_real_escape_string($conn, $row[0])
UPDATE:
In your latest attempt you have changed the array to an associative array, so this should do it:
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "hosts";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$client = array(
"0" => array("name" => "Peter Maxx", "ip" => "193.169.5.16"),
"1" => array("name" => "Ravi Shankar", "ip" => "193.169.5.17")
);
if(is_array($client)) {
$DataArr = array();
foreach($client as $row) {
$DataArr[] = "('". mysqli_real_escape_string($conn, $row["name"]) ."', '". mysqli_real_escape_string($conn, $row["ip"]) ."')";
}
$sql = "INSERT INTO ip_data (name, ip) VALUES ";
$sql .= implode(", " , $DataArr);
mysqli_query($conn, $sql);
}

Please change append to $DataArr[] to this one:
$DataArr[] = "('$fieldVal1', '$fieldVal2', '$fieldVal3')";

Correct
From
if(is_array($client) {
To
if(is_array($client)){
And your array $client will have only 2 elements in each iteration
From
# You will get PHP Warning: Illegal offset type
# since $row is already array
$fieldVal1 = mysqli_real_escape_string($client[$row][1]);
$fieldVal2 = mysqli_real_escape_string($client[$row][2]);
$fieldVal3 = mysqli_real_escape_string($client[$row][3]);
to
// For first iteration
// $row[0] = "Jerry Garcia"
// $row[1] = "193.169.5.11"
$fieldVal1 = mysqli_real_escape_string($conn, $row[0]);
$fieldVal2 = mysqli_real_escape_string($conn, $row[1]);
// $row[3] does not exists so comment it and set $fieldVal3 some data
// $row[3] not exists in your array and even $row[2]
// or add one value to your $client array and access using $row[2]
// $fieldVal3 = mysqli_real_escape_string($row[3]);
$fieldVal3 ='somedata';
and Finally
From
$DataArr[] = "('fieldVal1', 'fieldVal2', 'fieldVal3')";
To
$DataArr[] = "('$fieldVal1', '$fieldVal2', '$fieldVal3')";

Related

How do I "cancel" the update function in sql and php if there is an error?

I am taking data from Steam and due to their busy servers the data that I take doesn't come and then the data in my database gets updated to 0.00 which messes up everything. How could make it so that when I get the below error:
Undefined index: lowest_price in E:\Xampp\htdocs\dashboard\csgocasestats\php-scripts\eSports2013\eSports2013-3.php on line 19
that the data would not get updated if the error happens. And the error happens every time on different links (line).
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cases";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$filename_fnSt = "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Factory%20New%29";
$data_fnSt = file_get_contents($filename_fnSt);
$array_fnSt = json_decode($data_fnSt, true);
$lowest_price_fnSt = $array_fnSt["lowest_price"];
$fnSt = strtr("$lowest_price_fnSt","$"," ");
$filename_mnSt = "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Minimal%20Wear%29";
$data_mnSt = file_get_contents($filename_mnSt);
$array_mnSt = json_decode($data_mnSt, true);
$lowest_price_mnSt = $array_mnSt["lowest_price"];
$mnSt = strtr("$lowest_price_mnSt","$"," ");
$filename_ftSt = "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Field-Tested%29";
$data_ftSt = file_get_contents($filename_ftSt);
$array_ftSt = json_decode($data_ftSt, true);
$lowest_price_ftSt = $array_ftSt["lowest_price"];
$ftSt = strtr("$lowest_price_ftSt","$"," ");
$filename_wwSt = "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Well-Worn%29";
$data_wwSt = file_get_contents($filename_wwSt);
$array_wwSt = json_decode($data_wwSt, true);
$lowest_price_wwSt = $array_wwSt["lowest_price"];
$wwSt = strtr("$lowest_price_wwSt","$"," ");
$filename_bsSt = "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Battle-Scarred%29";
$data_bsSt = file_get_contents($filename_bsSt);
$array_bsSt = json_decode($data_bsSt, true);
$lowest_price_bsSt = $array_bsSt["lowest_price"];
$bsSt = strtr("$lowest_price_bsSt","$"," ");
$sql_querys = [
"UPDATE esports2013skins SET M4A4FadedZebra='$fnSt' WHERE id=6",
"UPDATE esports2013skins SET M4A4FadedZebra='$mnSt' WHERE id=7",
"UPDATE esports2013skins SET M4A4FadedZebra='$ftSt' WHERE id=8",
"UPDATE esports2013skins SET M4A4FadedZebra='$wwSt' WHERE id=9",
"UPDATE esports2013skins SET M4A4FadedZebra='$bsSt' WHERE id=10",
];
foreach($sql_querys as $sql){
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
The last advice you got in the previous question was wrong. You should be using prepared statements and parameter binding.
You also have a lot of code repetition. You can reduce all of it if you map an id with a URL and execute the same code for each item.
To avoid the problem with 0.00 inserted into the table, you need to check if the key lowest_price exists in the array. You can do so with isset
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cases";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4'); // always set the charset
// prepare SQL statement
$stmt = $conn->prepare('UPDATE esports2013skins SET M4A4FadedZebra=? WHERE id=?');
$stmt->bind_param('ss', $firstCol, $id);
$items = [
6 => "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Factory%20New%29",
7 => "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Minimal%20Wear%29",
8 => "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Field-Tested%29",
9 => "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Well-Worn%29",
10 => "https://steamcommunity.com/market/priceoverview/?appid=730&currency=1&market_hash_name=StatTrak™%20M4A4%20%7C%20Faded%20Zebra%20%28Battle-Scarred%29",
];
foreach ($items as $id => $filename_St) {
$array_St = json_decode(file_get_contents($filename_St), true);
// If there is lowest price the populate the bound variable and execute the query
if (isset($array_St["lowest_price"])) {
$lowest_price_ftSt = $array_St["lowest_price"];
$firstCol = strtr($lowest_price_ftSt, "$", " ");
$stmt->execute();
}
}

Inserting xml values in table no success

Trying to get my xml feed into a table, missing something as not working.
Warning: mysqli_query(): Couldn't fetch mysqli in
/Users/John/Sites/XMLproject/Update Emperor.php on line 77
//Database variables
$servername = "localhost";
$username = "Something";
$password = "Very secret";
$dbname = "TestDB";
$temptable = "wlbvx_jb_xml_emperor";
//Open database
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully to database: ","<strong>",$dbname,"</strong>","<br>" ;
?><br><?php
$url = "http://bookings.emperordivers.com/webScheduleSpecificXML_all.asp";
$feed = file_get_contents($url);
$xml = simplexml_load_string($feed);
//Row by row into variable, then into table
foreach ($xml->Schedule as $row) {
$ID = "Null";
$start = date("d-m-Y", strtotime($row->Start));
$duration = $row->Duration;
$boat = $row->Boat;
$itinerary = $row->Itinerary;
$spaces = $row->Spaces;
$rateseur = round(str_replace(',', '', $row->Rates->Rate[0]));
$rategbp = round(str_replace(',', '', $row->Rates->Rate[1]));
$rateusd = round(str_replace(',', '', $row->Rates->Rate[2]));
$sql = "INSERT INTO $temptable (id,xml_date, xml_duration, xml_boat, xml_itinerary, xml_spaces, xml_rate_eur, xml_rate_gbp, xml_rate_usd)VALUES ('{$ID}',{$start}', '{$duration}', '{$boat}', '{$itinerary}','{$spaces}', '{$rateseur}', '{$rategbp}', '{$rateusd}')";
echo "SQL Query to execute:",$sql,"<br>";
mysqli_query($conn, $sql);
}
What could cause the issue?

Why displaying array when select column in mysql?

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);

How to put the output query from mySQL to php int variable

I want to do a query to get the last id (int) in a table to create a new row with that last id + 1 but actually this just put all rows with the same id
my code:
<?php
$servername = "localhost";
$user = "root";
$pass = "dbpass";
$dbname = "site";
$mail = $_POST['mail'];
$password = $_POST['password'];
// Create connection
$conn = mysqli_connect($servername, $user, $pass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sqlID = "SELECT MAX(id) FROM `login`;";
if ($result = mysqli_query($conn, $sqlID)) {
$id = mysqli_fetch_row($result);
}
settype($id, "int");
$id = $id + 1;
$sql = "INSERT INTO login (`id`,`mail`,`password`)
VALUES ('".$id."','".$mail."','".$password."');";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
mysqli_fetch_row returns always an array, also if there is only 1 element. So the MAX(id) in in $row[0].
Fixing this, you also don't need to use settype.
If your id is autoincrement, change this:
$sql = "INSERT INTO login (`id`,`mail`,`password`)
VALUES ('".$id."','".$mail."','".$password."');";
to:
$sql = "INSERT INTO login (`mail`,`password`)
VALUES ('".$mail."','".$password."');";
Then get rid of all code from $sqlID to $id + 1; (for tidyness)

multi_query() has an error

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();
?>

Categories