Undefined index: ___mysqli_ston [duplicate] - php

This question already has answers here:
what is $GLOBALS["___mysqli_ston"] in mysqli
(2 answers)
Closed 1 year ago.
I am trying to parse some json data, into a mysql database, from a file. My original code was as follows:
<?php
$response = array();
$res=array();
$json = file_get_contents('C:\Users\Richard\Desktop\test.json');
if($json!=null){
$decoded=json_decode($json,true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if(is_array($decoded["configurationItems"]))
{
foreach($decoded["configurationItems"] as $configurationItems)
//for($i=0;$i>sizeof($decoded["configurationItems"]);$i++)
{
$configurationItemVersion=$configurationItems["configurationItemVersion"];
echo "<br />","configurationItemVersion:",$configurationItemVersion,"<br />";
$configurationItemCaptureTime=$configurationItems["configurationItemCaptureTime"];
echo "configurationItemCaptureTime:",$configurationItemCaptureTime,"<br />";
$configurationStateId=$configurationItems["configurationStateId"];
echo "configurationStateId:",$configurationStateId,"<br />";
$result = mysql_query("INSERT INTO configuration_item(configurationItemVersion,configurationItemCaptureTime,configurationStateId)
VALUES('$configurationItemVersion','$configurationItemCaptureTime','$configurationStateId')")or die("Insert Failed ".mysql_error());;
}// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
?>
which failed due to being depricated; so rather than altering the error handler to ignore this (really bad practice), I opted to convert to mysqli using a handy conversion tool sourced here : https://github.com/philip/MySQLConverterTool
I ran the converter on the aforementioned code and it generated the following:
<?php
$response = array();
$res=array();
$json = file_get_contents('C:\Users\Richard\Desktop\test.json');
if($json!=null){
$decoded=json_decode($json,true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if(is_array($decoded["configurationItems"]))
{
foreach($decoded["configurationItems"] as $configurationItems)
//for($i=0;$i>sizeof($decoded["configurationItems"]);$i++)
{
$configurationItemVersion=$configurationItems["configurationItemVersion"];
echo "<br />","configurationItemVersion:",$configurationItemVersion,"<br />";
$configurationItemCaptureTime=$configurationItems["configurationItemCaptureTime"];
echo "configurationItemCaptureTime:",$configurationItemCaptureTime,"<br />";
$configurationStateId=$configurationItems["configurationStateId"];
echo "configurationStateId:",$configurationStateId,"<br />";
$result = mysqli_query($GLOBALS["___mysqli_ston"], "INSERT INTO configuration_item(configurationItemVersion,configurationItemCaptureTime,configurationStateId)
VALUES('$configurationItemVersion','$configurationItemCaptureTime','$configurationStateId')")or die("Insert Failed ".((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error(
"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));;
}// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
?>
upon running this code I get the error message in the title (Undefined index: ___mysqli_ston) and have no idea how to fix it, any help would be much appreciated.
ps I am using the laravel framework if that makes a difference or opens up other solutions.
I now know that the error relates to the fact that I have no database connection string ie $GLOBALS["___mysqli_ston is generated by the generator.
it was my understanding that laravel took care of defining the database connection in its mvc architecture and therefore this does not need to be redefined. with that in mind what would my code look like ?

you must have connected to mysql using something like this
$con=mysqli_connect("localhost","my_user","my_password","my_db");
replace your this line
$result = mysqli_query($GLOBALS["___mysqli_ston"], "INSERT INTO configuration_item(configurationItemVersion,configurationItemCaptureTime,configurationStateId)
with this
$result = mysqli_query($con, "INSERT INTO configuration_item(configurationItemVersion,configurationItemCaptureTime,configurationStateId)

Related

Get last result from mysqli_multi_query

I'm creating PHP API for my Android application which will be used to scan QR codes. Part of that API is checking if scanned code is valid and can be scanned in a certain moment.
Whole checking part is a stored procedure in MariaDB database which is just executed by PHP script. Execution part in PHP is looking like this:
$sql = "CALL someProcedure('qr_code', #out); ";
$sql .= "SELECT #out AS `out`;";
if($conn->multi_query($sql)) {
while ($conn->more_results()) {
$conn->next_result();
}
$rs = $conn->store_result();
$row = $rs->fetch_assoc();
$odp = $row['out'];
if (!empty($rs)) {
$response['success'] = 1;
$response['message'] = $odp;
echo json_encode($response);
$rs->free();
} else {
$response['success'] = 0;
$response['message'] = mysqli_error($conn);
echo json_encode($response);
}
There are 4 results of that stored procedure:
scanned code doesn't exist,
scanned code is not an package (it is an articles code)
scanned code cannot be delivered just yet
scanning was successful
Now, when there is something wrong with the code, PHP part executes without a problem but if scanning is successful I would get a timeout (doesn't matter if it's default 30 seconds or 5 minutes).
The reason there is a timeout (I think) is that when scanning is successful there are some loops executed in Stored Procedure which may be returned in resultsets and choke PHP script ALTHOUGH when I execute that Stored Procedure in DBeaver (with exact same query as in PHP) there is no problem.
So, my question is what I can do about it? Removing the while loop in PHP script above makes the script execute without a problem (but I can't get the out parameter value.
Why not do two queries instead of one multi-query?
This is a respond to a comment by Rick James
Here's modified code:
$sql = "CALL ".$storedProcedure."(".$columns."); ";
$sql2 = "SELECT #out AS `out`;";
if($conn->query($sql)) {
if($rs = $conn->query($sql2)) {
$row = $rs->fetch_assoc();
$odp = $row;
if (!empty($odp)) {
$response['success'] = 1;
$response['message'] = $odp;
echo json_encode($response);
$rs->free();
} else {
$response['success'] = 0;
$response['message'] = mysqli_error($conn);
echo json_encode($response);
}
} else {
$response['success'] = 0;
$response['message'] = mysqli_error($conn);
echo json_encode($response);
}
And mysql error while executing the script:
{"success":0,"message":"Commands out of sync; you can't run this command now"}
The problem is when executing the second query.
I finally got it. All I had to do is to store results in every while loop iteration.
Here's how it looks now.
$sql = "CALL someProcedure('qr_code', #out); ";
$sql .= "SELECT #out AS `out`;";
if($conn->multi_query($sql)) {
while ($conn->more_results()) {
$rs = $conn->store_result();
$conn->next_result();
}
$rs = $conn->store_result();
$row = $rs->fetch_assoc();
$odp = $row['out'];
if (!empty($rs)) {
$response['success'] = 1;
$response['message'] = $odp;
echo json_encode($response);
$rs->free();
} else {
$response['success'] = 0;
$response['message'] = mysqli_error($conn);
echo json_encode($response);
}

JSON Decode elements in file

Hi I am currently working on stripping out a json file and putting the elements into a database there are 26 entries in the json file using the following code I have been able to map the majority of the entries but am now in a position whereby certain elements in the json only occur in certain entries eg tags in the first 2 entries has a Name and cirrushq_id field but from the 3rd entry down has only a aws:autoscaling:groupName not present in the first 2 entries so my question really is how to modify the php such that it takes into account the fact that there may not be a Name or id for every entry and not subsequently break ?
here is the php
<?php
$con=mysqli_connect("localhost","root","","json_map");
$response = array();
$res=array();
$json = file_get_contents('C:\Users\Richard\Desktop\test.json');
if($json!=null){
$decoded=json_decode($json,true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if(is_array($decoded["configurationItems"]))
{
foreach($decoded["configurationItems"] as $configurationItems)
//for($i=0;$i>sizeof($decoded["configurationItems"]);$i++)
{
$Name=$configurationItems["tags"]["Name"];
echo "Name:",$Name,"<br />";
$cirrushq_id=$configurationItems["tags"]["cirrushq_id"];
echo "cirrushq_id:",$cirrushq_id,"<br />";
$awsautoscalinggroupName= $configurationItems["tags"]["aws:autoscaling:groupName"];
echo "aws:autoscaling:groupName:",$awsautoscalinggroupName,"<br />";
$result = mysqli_query($con, "INSERT INTO tag(name, cirrushq_id, aws_autoscaling_group_name)
VALUES('$Name','$cirrushq_id', '$awsautoscalinggroupName')")or die("Insert Failed ".((is_object($con)) ? mysqli_error($con) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));;
}// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored tags ";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
?>
and the json
{
"fileVersion":"1.0",
"configurationItems":[
{
"configurationItemVersion":"1.0",
"configurationItemCaptureTime":"2014-12-05T10:22:51.751Z",
"configurationStateId":1,
"relatedEvents":[ ],
"awsAccountId":"",
"configurationItemStatus":"ResourceDiscovered",
"resourceId":"",
"ARN":"",
"awsRegion":"us-east-1",
"availabilityZone":"us-east-1b",
"configurationStateMd5Hash":"",
"resourceType":"AWS::EC2::Instance",
"resourceCreationTime":"2014-01-06T10:37:37.000Z",
"tags":{
"Name":"dbn.prod-us.wordeo.com",
"cirrushq_id":"instance_20"
},
as above for 2nd entry
3rd entry the same down to tags as follows
"tags":{
"aws:autoscaling:groupName":"ES-PROD-US-03-01-14"
},
using isset method as per answer
<?php
$con=mysqli_connect("localhost","root","","json_map");
$response = array();
$res=array();
$json = file_get_contents('C:\Users\Richard\Desktop\test.json');
if($json!=null){
$decoded=json_decode($json,true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if(is_array($decoded["configurationItems"]))
{
foreach($decoded["configurationItems"] as $configurationItems)
//for($i=0;$i>sizeof($decoded["configurationItems"]);$i++)
$tags=$configurationItems["tags"];
if(isset($tags["Name"]) && isset($tags["cirrushq_id"])){
$Name=$tags["Name"];
echo "Name:",$Name,"<br />";
$cirrushq_id=$tags["cirrushq_id"];
echo "cirrushq_id:",$cirrushq_id,"<br />";
$awsautoscalinggroupName= isset($tags["aws:autoscaling:groupName"]) ?
$tags["aws:autoscaling:groupName"] : '';
echo "aws:autoscaling:groupName:",$awsautoscalinggroupName,"<br />";
$result = mysqli_query($con, "INSERT INTO tag(name, cirrushq_id, aws_autoscaling_group_name)
VALUES('$Name','$cirrushq_id', '$awsautoscalinggroupName')");
}// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored tags ";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
?>
Use isset() to check the name or id exists or not.
Change the php foreach loop code like,
$tags=$configurationItems["tags"];
if(isset($tags["Name"]) && isset($tags["cirrushq_id"])){
$Name=$tags["Name"];
echo "Name:",$Name,"<br />";
$cirrushq_id=$tags["cirrushq_id"];
echo "cirrushq_id:",$cirrushq_id,"<br />";
$awsautoscalinggroupName= isset($tags["aws:autoscaling:groupName"]) ?
$tags["aws:autoscaling:groupName"] : '';
echo "aws:autoscaling:groupName:",$awsautoscalinggroupName,"<br />";
// remove the die if there is any error then it will go forward
$result = mysqli_query($con, "INSERT INTO tag(name, cirrushq_id, aws_autoscaling_group_name)
VALUES('$Name','$cirrushq_id', '$awsautoscalinggroupName')");

json decoding in php and insert into mysql DB

this is my json data, i am try to decode this json and store the data in mysql database.
i am try json decoding in php. In my php server side json data are not decoded and not stored in mysql database. please help me to solve this problem.
JSON DATA
{
"code":"0",
"message":"Success",
"events":[
{
"id":1,
"name":"test event",
"description":"test desc",
"date":"2014-06-22 00:00:00",
"location":"keelapalur",
"type":1,
"passcode":"123456",
"created":{
"date":"2014-06-08 17:05:12",
"timezone_type":3,
"timezone":"UTC"
},
"updated":{
"date":"2014-06-08 17:05:12",
"timezone_type":3,
"timezone":"UTC"
}
},
{
"id":2,
"name":"rtyr",
"description":"rtyr",
"date":"2014-06-22 00:00:00",
"location":"try",
"type":1,
"passcode":"123456",
"created":{
"date":"2014-06-12 09:26:31",
"timezone_type":3,
"timezone":"UTC"
},
"updated":{
"date":"2014-06-12 09:26:31",
"timezone_type":3,
"timezone":"UTC"
}
}
]
}
PHP code
<?php
$response = array();
$res=array();
require_once __DIR__ . '/db_connect.php';
$json = file_get_contents('/insert.json');
if($json!=null){
$decoded=json_decode($json,true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if(sizeof($decoded["events"])>0)
{
for($i=0;$i>sizeof($decoded["events"]);$i++)
{
$id=$decoded["events"]["id"];
$name=$decoded["events"]["name"];
$date=$decoded["events"]["date"];
$desc=$decoded["events"]["description"];
$location=$decoded["events"]["location"];
$type=$decoded["events"]["type"];
$passcode=$decoded["events"]["passcode"];
$cdate=$decoded["events"]["created"]["date"];
$ctimzonety= $decoded["events"]["created"]["timezone_type"];
$ctimz=$decoded["events"]["created"]["timezone"];
$udate=$decoded["events"]["updated"]["date"];
$utimzonety= $decoded["events"]["updated"]["timezone_type"];
$utimz=$decoded["events"]["updated"]["timezone"];
$result = mysql_query("INSERT INTO events(userid,name,desc,date,loc,type,passcode,cdate,ctimezone_type,ctimezone,udate,utimezone_type,utimezone)
VALUES('$id,'$name','$desc','$date','$loc','$type','$passcode','$cdate','$ctimzonety','$ctimz','$udate','$utimzonety','$utimz')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
}
?>
Make ensure your database connectivity..Try this code 100% it's working...
<?php
$response = array();
$res=array();
$json = file_get_contents('C:\Users\Devunne3\Desktop\insert.json');
if($json!=null){
$decoded=json_decode($json,true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if(is_array($decoded["events"]))
{
foreach($decoded["events"] as $events)
//for($i=0;$i>sizeof($decoded["events"]);$i++)
{
$id=$events["id"];
echo "<br />","userid:",$id,"<br />";
$name=$events["name"];
echo "name:",$name,"<br />";
$date=$events["date"];
echo "date:",$date,"<br />";
$desc=$events["description"];
echo "desc:",$desc,"<br />";
$location=$events["location"];
echo "loc:",$location,"<br />";
$type=$events["type"];
echo "type:",$type,"<br />";
$passcode=$events["passcode"];
echo "passcode:",$passcode,"<br />";
$cdate=$events["created"]["date"];
echo "cdate:",$cdate,"<br />";
$ctimzonety=$events["created"]["timezone_type"];
echo "ctimezone_type:",$ctimzonety,"<br />";
$ctimz=$events["created"]["timezone"];
echo "ctimezone:",$ctimz,"<br />";
$udate=$events["updated"]["date"];
echo "udate:",$udate,"<br />";
$utimzonety=$events["updated"]["timezone_type"];
echo "utimezone_type:",$utimzonety,"<br />";
$utimz=$events["updated"]["timezone"];
echo "utimezone",$utimz,"<br />";
echo"------------------------------------------------","<br />";
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("INSERT INTO events(userid,name,desc,date,loc,type,passcode,cdate,ctimezone_type,ctimezone,udate,utimezone_type,utimezone)
VALUES('$id','$name','$desc','$date','$location','$type','$passcode','$cdate','$ctimzonety','$ctimz','$udate','$utimzonety','$utimz')")or die("Insert Failed ".mysql_error());;
}// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
?>

php mysql how to fix this error :Undefined variable :id in C:\

how to fix the error:
Undefined variable : id in c:\wamp\www\android_connect\status.php in 38
what i am doing wrong ???
status.php
<?php
ob_start();
session_start();
//array for JSON response
$response = array();
if(isset($_SESSION['id']))
{
$id= $_SESSION['id'];
}
//var_dump ($id);
// include db connect class
require_once '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for required fields
if(empty($_POST['status'])){
$response["success"] = 0;
$response["message"] = "Your Text Field is empty";
// echoing JSON response
die (json_encode($response));
}
else if (isset($_POST['status'])) {
$status = $_POST['status'];
$sql = mysql_query("INSERT INTO status (status_text, uid)VALUES('$status', '$id')")or die(mysql_error());
if ($sql) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Status Saved.";
// echoing JSON response
die (json_encode($response));
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Error in saving the status.";
// echoing JSON response
die (json_encode($response));
}
}
ob_end_flush();
?>
the error is in the insert query but i do not know how to fix it.
it have something with the $_SESSION can anyone help me ??
The error you get means $id is unset. In your code there isn't a check for the $id variable.
Change else if (isset($_POST['status'])) { to else if (isset($_POST['status']) && isset($id)) {
and add an else statement, something like this:
else {
// failed to insert row because of missing $id
$response["success"] = 0;
$response["message"] = "Error in saving the status, session variable $id missing";
// echoing JSON response
die (json_encode($response));
}
Change the insert query like this,
$sql = mysql_query("INSERT INTO status (status_text, uid)VALUES('".$status."', '".$id."')")or die(mysql_error());

mysql query and encoding it in json format

I'm using this simple php code to encode the MySql query result in json format.
But Don't know why it is not giving me the desirable output.
I'm actually trying to get the employee details by entering their 'employee_number'.
<?php
require('DB_Connect.php');
require('config.php');
// check for post data
/*
if (isset($_POST["employee_number"])) {
$employee_name = $_POST['employee_number'];
*/
//get a employee from employee_info table
$result = mysql_query("SELECT *FROM employee_info WHERE employee_number =9876543210");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
echo("Success !! Yoo");
$employee = array();
$employee["employee_number"] = $result["employee_number"];
$employee["employee_name"] = $result["employee_name"];
$employee["flag"]=$result["flag"];
// success
$response["success"] = 1;
// user node
$response["employee"] = array();
array_push($response["employee"], $employee);
// echoing JSON response
echo json_encode($response);
} else {
// no employee found
$response["success"] = 0;
$response["message"] = "No employee found";
// echo no users JSON
echo json_encode($response);
}
}else {
// no employee found
$response["success"] = 0;
$response["message"] = "No employee found";
// echo no users JSON
echo json_encode($response);
}
/*} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
*/
// echoing JSON response
echo json_encode($response);
?>
mysql_query is deprecated. Use mysqli or PDO instead.
make sure you format your query properly *note the spaces
$result = mysql_query("SELECT * FROM employee_info WHERE employee_number = 9876543210");
you could also just echo the $result as your employee array doesn't seem to do anything.
echo json_encode($result);

Categories