Getting an array from Android Client. Storing it in the DB gives a Notice: Undefined offset: 1 in C:\filepath\ on line 67
I am trying to achieve this in my DB:
User_Id | Book_Id
---------|---------
3 | 120
---------|---------
1 | 17
---------|---------
php file that collects the post from android client:
if(isset($_POST['watch'])){
$jsonwatch = $_POST['watch'];
$array = json_decode($jsonwatch, true);
$response["error"] =! ($db_watch->storeClass($array['attendees'], $array['lesson_iDs']));
}
php file that is called in the notice:
public function storeClass($attendees, $lesson_iDs) {
$stmt = $this->conn->prepare("INSERT INTO watch (date, user_id, lesson_id) VALUES(NOW(), ?, ?)");
$stmt->bind_param("ii", $attendees, $lesson_id);
foreach ($attendees as $index => $attendee) {
$lesson_id = $lesson_iDs[$index]; // Line 67
$result = $stmt->execute();
if(!$result){
echo '\n';
printf("Error for attendee %d in lesson %d : %s.\n", $attendee, $lesson_id, $stmt->error);
echo '\n';
echo '\n';
}
}
$stmt->close();
// result
return $result;
}
UPDATE!
var_dump($array):
C:\wamp64\www\ghanaweb\AddClass.php:19:
array (size=4)
'attendees' =>
array (size=2)
0 => string '5a6611e89e9e26.27646060' (length=23)
1 => string '5a4cfae69fd7b6.01373362' (length=23)
'id' => int 0
'lesson_iDs' =>
array (size=1)
0 => int 4
'lesson_id' => int 0
{"error":false}
Your problem is that you use the $ index as the ID in your case and it's only the number of the masive and nothing more
Try to use
$lesson_id = $lesson_iDs[$attendee['lesson_id']];
$lesson_iDs array has only one element and in the for loop you are trying to access a second element which is not existing
Related
I'm getting a fatal error every time my PHP script is run. Despite that, all of the data is still uploaded to the database. When $values[0] is echoed, there are no NULL values as the error states, and everything is normal. I'm quite confused.
Error
[02-Oct-2018 19:59:54 America/Vancouver] PHP Warning: Invalid argument supplied for foreach() in /home1/antonfa1/public_html/trading-history/process.php on line 22
[02-Oct-2018 19:59:54 America/Vancouver] PHP Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'trade_date' cannot be null in /home1/antonfa1/public_html/trading-history/process.php:48
Stack trace:
#0 /home1/antonfa1/public_html/trading-history/process.php(48): PDOStatement->execute(Array)
#1 {main}
thrown in /home1/antonfa1/public_html/trading-history/process.php on line 48
The strange thing is that I didn't seem to be getting this warning and error yesterday, so I commented out all of the modifications that I had made since then, but the issue persists.
Script
include 'includes/connect.php';
$stri = 'INSERT INTO trades (trade_date, trade_time, trade_datetime, trade_transaction, trade_symbol, trade_status, trade_quantity, trade_filled, trade_price, trade_value) VALUES (:date, :time, :datetime, :transaction, :symbol, :status, :quantity, :filled, :price, :value)';
$file = fopen($_SESSION['file'], 'r');
while (!feof($file)) {
$values = [];
foreach (fgetcsv($file) as $key => $value) {
array_push($values, $value);
}
echo $values[0] . '<br>';
$stat = $conn->prepare($stri);
$stat->execute([
'date' => $values[0],
'time' => $values[1],
'datetime' => $values[2],
'transaction' => $values[3],
'symbol' => $values[4],
'status' => $values[5],
'quantity' => $values[6],
'filled' => $values[7],
'price' => $values[8],
'value' => $values[9],
]);
}
Is fgetcsv($file) as $key => $value really an invalid argument? Is this what's potentially causing this "false" error? I wasn't getting this warning yesterday :/
Echo
2018-10-02
2018-10-02
2018-10-02
2018-10-02
2018-10-02
2018-10-02
2018-10-02
2018-10-02
2018-10-02
2018-10-02
2018-10-02
2018-10-02
2018-10-02
2018-10-02
All of the data points are there and none are NULL...
Your issue is that fgetcsv() returns false when it reaches the end of the file...
fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other errors, including end of file.
You can use fgetcsv() in the same way you're using feof() to only loop while there are records to be found.
For example
$stri = <<<_SQL
INSERT INTO trades (
trade_date,
trade_time,
trade_datetime,
trade_transaction,
trade_symbol,
trade_status,
trade_quantity,
trade_filled,
trade_price,
trade_value
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
_SQL; // note the positional placeholders
$stat = $conn->prepare($stri); // prepare once, not in a loop
$file = fopen($_SESSION['file'], 'r');
while($values = fgetcsv($file)) { // EOF will return false and exit the loop
if (count($values) === 10) {
echo $values[0] . '<br>';
$stat->execute($values);
} else {
echo 'Skipping invalid record';
}
}
fclose($file);
If you use positional placeholders, you don't need to construct an associative array for the prepared statement.
Your PDO parameters need to be passed like this:
$statement->execute([
':foo' => 1,
':bar' => '2001-01-01',
':baz' => 42
]);
You are missing the : part of the key passed to PDOStatement::execute
So I have been doing my research and no method seems to parse my file correctly. I have tried these two codes, my data is being inserted into sql however it is inserted 3 times with the first insertion being fine while the other 2 are blank. Here is my JSON file and code:
JSON:
[
{
"Comments": {
"Manufacturer": "--E",
"Model": "----- ----- ----",
"BIOSFamily": "---",
"BIOSDate": --/--/---8",
"SerialNumber": "---------"
}
},
{
"#ComputerSystem.v1-----------ystem": {
"/redfish/v1/Systems/1/": {
"AssetTag": " ",
"Bios": {
"#odata.id": "/redfish/v1/systems/1/bios/"
},
"BiosVersion": "U----------------)",
"Boot": {
"BootSourceOverrideMode": "-----y",
"BootSourceOverrideTarget": "None",
"BootSourceOverrideEnabled": "Disabled",
"BootSo-----------arget#Redfish.AllowableValues": [
"None",
"Cd",
"Hdd",
"Usb",
"Utilities",
"Diags",
"BiosSetup",
"Pxe",
"UefiShell"
]
Code:
<?php
$connect = mysqli_connect("reserve1",
"root", "","server_31");
$filename = "-----.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach($array as $row)
{
$sql = "INSERT INTO servers (Model,
Manufacturer, BIOSFamily,
BIOSDate,
SerialNumber) VALUES
('".$row["Comments"]["Model"]."' ,
'".$row["Comments"]
["Manufacturer"]."',
'".$row["Comments"]
["BIOSFamily"]."','".$row["Comments"]
["BIOSDate"]."','".$row["Comments"]
["SerialNumber"]."')";
mysqli_query($connect, $sql);
}
echo "Data in";
?>
ERROR:" Notice: Undefined index: Comments "
other forloops i have tried are:
foreach($data as $Comments)
{
$sql =" INSERT INTO
'servers'('Manufacturer','Model',
'BIOSFamily','BIOSDate',
'SerialNumber'), VALUES('{$Comments-
>Manufacturer}', '{$Comments-
>Model}',
'{$Comments->BiosFamily}',
'{$Comments->BiosDate}',
'{$Comments-
>SerialNumber}')";
}
ERROR:" Notice: Trying to get property of non-object in"
To reiterate: the first method does get my info onto sql but does so 3 times with the last 2 entries being blank. The second method does not insert anything into my table.
EDIT:
so i tried vardump, using the file itself all i got was NULL, copy and pasting the contents and labeling it $json= ' content ' in the script i get..
C:\Users\Administrator\Desktop\Reserve1\newtry\NEWJSONP.php:16:
array (size=1)
0 =>
object(stdClass)[1]
public 'Comments' =>
object(stdClass)[2]
public 'Manufacturer' => string 'HPE' (length=3)
public 'Model' => string '-------------' (length=20)
public 'BIOSFamily' => string '---' (length=3)
public 'BIOSDate' => string '--/--/----' (length=10)
public 'SerialNumber' => string '-------' (length=10)
C:\Users\Administrator\Desktop\Reserve1\newtry\NEWJSONP.php:17:
array (size=1)
0 =>
array (size=1)
'Comments' =>
array (size=5)
'Manufacturer' => string '---' (length=3)
'Model' => string '------ ----------' (length=20)
'BIOSFamily' => string '---' (length=3)
'BIOSDate' => string '--/--/----' (length=10)
'SerialNumber' => string '-------' (length=10)
Simply index in your foreach loop the first item since $array object maintains Comments only in first position. See 0 index from var_dump output:
array (
0 =>
array (
'Comments' =>
array (
'Manufacturer' => '--E',
'Model' => '----- ----- ----',
'BIOSFamily' => '---',
'BIOSDate' => ' --/--/-- - 8 ',
'SerialNumber' => '---------',
),
),
1 =>
array (
'#ComputerSystem.v1-----------ystem' =>
...
Therefore, iterate through the Comments array and use parameterization for readability:
$connect = new mysqli($servername, $username, $password, $dbname);
// PREPARED STATEMENT
$sql = "INSERT INTO servers (Model, Manufacturer, BIOSFamily, BIOSDate, SerialNumber)
VALUES(?, ?, ?, ?, ?)";
// INDEX FIRST ITEM AT 0
foreach($array[0] as $row) {
$stmt = $connect->prepare($sql);
// BIND PARAMETERS (NO COMMENTS INDEX)
$stmt->bind_param("sssss", $row["Model"],
$row["Manufacturer"],
$row["BIOSFamily"],
$row["BIOSDate"],
$row["SerialNumber"]);
// EXECUTE STATEMENT
$result = $stmt->execute();
}
i try show data using PDO. But i get Error "Trying to get property of non-object".
i have a simple script.
public function tampilUserId($user_id)
{
$sql = "SELECT $this->user.*, $this->provinsi.*
FROM $this->user
INNER JOIN $this->provinsi
ON $this->user.provinsi_id=$this->provinsi.provinsi_id
WHERE user_id=:user_id";
$stmt = db::prepare($sql);
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_OBJ);
}
And this
echo $results->email_user;
print_r($result);
result
Notice: Trying to get property of non-object in C:\xampp\htdocs\laporan_app\user_views\profile.php on line 35
stdClass Object ( [user_id] => 45 [nama_dpn_user] => [nama_blkng_user] => [username_user] => adi [password_user] => $2y$10$p/8gF5BcQSooQUKRlEAiPuOSy4o1RMeXA5Ul8GTZNYZi/4wcOP3Ja [email_user] => adi#gmail.com [level_user] => mahasiswa [img_user] => [_dir_img_user] => [_size_img_user] => [provinsi_id] => [universitas_id] => )
And i try this script
echo $results['email_user'];
print_r($results);
result
Notice: Undefined index: email_user in C:\xampp\htdocs\laporan_app\user_views\profile.php on line 35
stdClass Object ( [user_id] => 45 [nama_dpn_user] => [nama_blkng_user] => [username_user] => adi [password_user] => $2y$10$p/8gF5BcQSooQUKRlEAiPuOSy4o1RMeXA5Ul8GTZNYZi/4wcOP3Ja [email_user] => adi#gmail.com [level_user] => mahasiswa [img_user] => [_dir_img_user] => [_size_img_user] => [provinsi_id] => [universitas_id] => )
Please help me, thanks before.
Merdeka! :D
In case your SQL query not contain any error its mean data was successfully pulled from database. So in your tampilUserId($user_id) function, its returning set of array from $stmt->fetchAll(PDO::FETCH_OBJ). Like below:
/* Sample from Sakila database */
array (size=603)
0 =>
object(stdClass)[11]
public 'address_id' => string '1' (length=1)
public 'address' => string '47 MySakila Drive' (length=17)
public 'address2' => null
public 'district' => string 'Alberta' (length=7)
public 'city_id' => string '300' (length=3)
public 'postal_code' => string '' (length=0)
public 'phone' => string '' (length=0)
public 'last_update' => string '2014-09-25 22:30:27' (length=19)
1 =>
object(stdClass)[12]
public 'address_id' => string '2' (length=1)
public 'address' => string '28 MySQL Boulevard' (length=18)
public 'address2' => null
public 'district' => string 'QLD' (length=3)
public 'city_id' => string '576' (length=3)
public 'postal_code' => string '' (length=0)
public 'phone' => string '' (length=0)
public 'last_update' => string '2014-09-25 22:30:09' (length=19)
more elements...
All you need to do is looping your function returned value first whereever you call it. Short example from your case:
//I dont know you put it under class or not.
$data = $YourClass->tampilUserId($user_id);
foreach ($data as $item) {
echo $item->email_user);
}
Note:
You can manually echoing your data without looping and its bad practice because you dont know the length of the array. So this is just gusessing. Taken from your case it would be.
$data = $YourClass->tampilUserId($user_id);
$data[0]->email_user; //If an object
$data[0]['email_user']; //If an array
Update:
There is suspicious thing on your query. The variable $this->user is not look like column name to me(unsure) If yes, so you have small mistake on your query. Secondly, as you said the result is null its mean something wrong or data you search not exist. I put this sample running inner join query.
Example:
Lets said i had 2 table. 1st is address and 2nd is city
|address table|
|city table|
So your sql query for joining table(from image above) should be:
SELECT adr.address_id, adr.address, adr.district, adr.city_id, c.city_id,
c.city FROM address AS adr INNER JOIN city AS c ON adr.city_id = c.city_id
WHERE c.city_id = 300 #using city id
Output:
Bring it to PHP
<?php
$pdo= new PDO('mysql:dbname=sakila;host=localhost:3306', 'user', password');
$city_id = 300; // manual set
$sql = 'SELECT adr.address_id, adr.address, adr.district, adr.city_id,
c.city_id, c.city FROM address AS adr INNER JOIN city AS c ON
adr.city_id = c.city_id WHERE c.city_id = :city_id';
$stmt = $_this->db->prepare($sql);
$stmt->bindParam(':city_id', $city_id);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
?>
var_dump($data) giving a result:
Great, as it come as (object(stdClass)) so we can loop it through the array & then accessing it using -> sign.
<?php
$i = 1;
foreach ($data as $d) {
echo '<dl>';
echo '<dt>Adress '.$i++.':</dt>';
echo '<li>Address id: '.$d->address_id.'</li>';
echo '<li>Address: '.$d->address.'</li>';
echo '<li>District: '.$d->district.'</li>';
echo '<li>City id: '.$d->city_id.'</li>';
echo '<li>City name: '.$d->city.'</li>';
echo '</dl>';
}
?>
Result in browser:
Hope this will resolve your problem.
I've spent hours looking at this and just don't see the mistake.
6 columns, 6 ?'s, 6 array elements.
The insert works fine the update is the problem!
Btw. is this a good way to deal with insert on duplicate update?
$userId = 13;
foreach($tableKey as $table=>$value){
foreach($value as $key=>$val){
$array_of_parameters[$key] = $val;
$fields[] = sprintf("%s=?", $key);
}
$field_list = join(', ', $fields);
try{
$update = "UPDATE `$table` SET $field_list WHERE id=$userId";
$stmt = $db->prepare($update);
echo $stmt->debugDumpParams();
$stmt->execute($array_of_parameters);// here's where I get error!
if($stmt->rowCount() == 0){
$insert = "INSERT INTO `$table` (".implode(',', array_keys($value)).") VALUES (:".implode(',:', array_keys($value)).")";
$stmt = $db->prepare($insert);
echo $stmt->debugDumpParams();
$stmt->execute($array_of_parameters);
}
}
}
Here's the debug and $array_of_parameters
array
'user' => string 'somebody' (length=3)
'first' => string 'some' (length=7)
'last' => string 'body' (length=4)
'zoneId' => string 'zone' (length=4)
'email' => string 'tst#me.net' (length=21)
'head' => string '1' (length=1)
SQL: [80] UPDATE `user` SET user=?, first=?, last=?, zoneId=?, email=?, head=? WHERE id=13 Params: 0
And of course the error
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
Try calling array_values on $array_of_parameters before executing the statement.
For unnamed parameters, execute probably expects numeric (default) keys in your parameters array. Populate $array_of_parameters in order without keys, then try it.
Please I have a table with three columns :
id (this is the id of my table)
parent (this is the parent)
position (and this is the position)
And I have this array $_arr['menu'] :
array (size=3)
13 =>
array (size=1)
'parent' => string '0' (length=1)
14 =>
array (size=1)
'parent' => string '13' (length=2)
25 =>
array (size=1)
'parent' => string '0' (length=1)
I want to update may table with those values in the array $_arr['menu'].
I imagine to do something like but in one query (perhaps using case in) :
UPDATE table SET position = 1, parent = 0 WHERE id = 13;
UPDATE table SET position = 2, parent = 13 WHERE id = 14;
UPDATE table SET position = 3, parent = 0 WHERE id = 25;
Please masters, how to get those values from that array and how to do the update !
Thanks a lot
I'm not sure I got your question, but I'll write my snippet. (I don't remember php syntax well and it's not tested, but I think it shows what I want to say)
try {
$db->beginTransaction();
$increment = 0;
foreach ($arr as $id => $innerArray) {
$db->query("UPDATE table SET position = ".(++$increment).", parent = ".$innerArray['parent']." WHERE id =".$id);
}
$db->commit();
} catch (Exception $e) {
$db->rollback();
}