Hi I am creating some dummy data in a sql statement and returning the data in a jso n format. I believe I am connecting to the mysql db ok through odbc. However the dataset appears to be empty when I run the same query in workbench it returns data ok.
This is how the data is returned to the webpage making the call
"[{"coords":{"lat":null,"lng":null},"iconImage":null,"content":null},{"coords":{"lat":null,"lng":null},"iconImage":null,"content":null}]
here is my code I have no error messages just empty json.
require("../PHP/phpsqlajax_dbinfo.php");
$connection=odbc_connect($database, $username, $password);
if (!$connection)echo 'Failed to connect';
//Select Test statement
$query="select 53.745 as lat,-0.338 as lng,'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png' as iconImage, '<h1>Tony G</h1>' as content union all
select 53.745 as lat,-0.310 as lng,'https://maps.gstatic.com/mapfiles/ms2/micons/blue.png' as iconImage, '<h1>fred</h1>' as content ";
$result=odbc_exec($connection,$query);
//work through result and create JSON
while ($row = odbc_fetch_row($result)){
$json[] = [
'coords' => ['lat' => $row['lat'],'lng' => $row['lng']],
'iconImage' => $row['iconImage'],
'content' => $row['content'],
];
}
echo json_encode($json);
I am a little puzzled as to what I am doing wrong.
thanks
Though it's unclear from manual where does data go to in odbc_fetch_row, it's clear that result (true or false) of this function is not what you expect. So, you should use another function, which returns array, in this case it is odbc_fetch_array:
while ($row = odbc_fetch_array($result)){
$json[] = [
'coords' => ['lat' => $row['lat'],'lng' => $row['lng']],
'iconImage' => $row['iconImage'],
'content' => $row['content'],
];
}
Related
When i run the following script. The row is inserted twice ( the query runs twice ) .
require_once $_SERVER['DOCUMENT_ROOT'].'/functions/sanitize.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/main/config.php';
$response = textsanitize($_POST['r']);
$ticket = idssanitize($_POST['t']);
$stmt = $condb->prepare("INSERT INTO ticket_reponses (ticket_id,user_id,time,response) VALUES (:ticket_id,:user_id,:time,:response)");
$stmt->execute(
array(
"ticket_id" => $ticket,
"user_id" => $_SESSION['user_id'],
"time" => time(),
"response" => $response
)
);
if($stmt->execute()){
echo "SUCCESS";
}
When i remove if($stmt->execute()){echo "SUCCESSS";}. It runs in the right way. The row inserted once.
Why does if($stmt->execute()) execute the query again ? I thought that if($stmt->execute()) only returns TRUE || FALSE. I want to ensure that the query was executed successfully.
One of the good uses of prepared statements in any language is that you can prepare it once and then execute it as many times as needed.
So in your case you execute() the statement twice, but it's possible that you could insert a whole bunch of data with the same prepared statement in a loop. Each time you call execute() you can just pass a new set of values to run the prepared statement. In your case it is an INSERT, so this is run twice.
In your case you probably just need...
$stmt = $condb->prepare("INSERT INTO ticket_reponses (ticket_id,user_id,time,response) VALUES (:ticket_id,:user_id,:time,:response)");
if($stmt->execute(array(
"ticket_id" => $ticket,
"user_id" => $_SESSION['user_id'],
"time" => time(),
"response" => $response))) {
echo "SUCCESS";
}
It is because it is calling the $stmt->execute() function twice. Once before the if statement and once as the condition in the if statement.
So, you need to remove one instance of it.
I believe that you need to check if the statement has executed correctly (hence the if). So, the code can be like...
require_once $_SERVER['DOCUMENT_ROOT'].'/functions/sanitize.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/main/config.php';
$response = textsanitize($_POST['r']);
$ticket = idssanitize($_POST['t']);
$stmt = $condb->prepare("INSERT INTO ticket_reponses (ticket_id,user_id,time,response) VALUES (:ticket_id,:user_id,:time,:response)");
$values = array(
"ticket_id" => $ticket,
"user_id" => $_SESSION['user_id'],
"time" => time(),
"response" => $response
);
if($stmt->execute($values)){
echo "SUCCESS";
}
You are executing $stmt->execute() twice, so it's simply inserting two rows. no rocket science here.
if you want to check if the query ran successfully or not do it in the first statement itself.
require_once $_SERVER['DOCUMENT_ROOT'].'/functions/sanitize.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/main/config.php';
$response = textsanitize($_POST['r']);
$ticket = idssanitize($_POST['t']);
$stmt = $condb->prepare("INSERT INTO ticket_reponses (ticket_id,user_id,time,response) VALUES (:ticket_id,:user_id,:time,:response)");
$isSuccessful = $stmt->execute(
array(
"ticket_id" => $ticket,
"user_id" => $_SESSION['user_id'],
"time" => time(),
"response" => $response
)
);
if($isSuccessful){
echo "SUCCESS";
}
the following code is not working as expected, the echo statement never return any response to the client side and it is hang.
$query = "INSERT INTO Tasks (ProjectID,Title,Start,End,PercentComplete,ParentID,OrderID,Summary,Expanded,LastUpdate)
VALUES($project_Id, '$title','$start','$end','$percentComplete',$parentID,'$orderID','$summary','$expanded',NOW())";
$result = mysqli_query($con, $query);
if ($result) {
$last_id = mysqli_insert_id($con);
echo json_encode(array(ID => $last_id, Title => $title, Start => $start, End => $end, percentComplete => $percentComplete));
}
However, if I added one more line of echo as follows, both the echo statement is able to be received on the client side.
$query = "INSERT INTO Tasks (ProjectID,Title,Start,End,PercentComplete,ParentID,OrderID,Summary,Expanded,LastUpdate)
VALUES($project_Id, '$title','$start','$end','$percentComplete',$parentID,'$orderID','$summary','$expanded',NOW())";
$result = mysqli_query($con, $query);
if ($result) {
$last_id = mysqli_insert_id($con);
echo json_encode(array(ID => $last_id, Title => $title, Start => $start, End => $end, percentComplete => $percentComplete));
echo 1;
}
I cannot figure out what is wrong here, please help to advice on this. Thanks
Try setting the output headers in your controller like this (before the output is sent back i.e. before json_encode):
$this->output->set_header('Content-Type: application/json; charset=utf-8');
And as mentioned in earlier answer, use quotes around your array keys.
it turns out that there is a for loop in the javascript which initiate the request. The for loop send lot of $_POST and the response is actually returned to client side after a long time (~5 minutes).
You are defining your array keys as constants. They need to be quoted. take a look at the following array definiton.
$array = array(
'id' => $id,
'title' => $title,
);
Notice that I have used ' to quote my keys?
You can identify your issue by enabling error reporting:
error_reporting(E_ALL);
ini_set('display_errors', 'On');
It will then show you an error:
Notice: Undefined constant '...'
In depth
To explain a little better what's going wrong in your syntax you will first need to understand what constants are. Constants are similiar to variables. The only difference is that they have to be defined at the top of your script and that the value can not be changed (or better said is constant).
To define a constant you would use:
define('constantname', 'constantvalue');
However, for your code to work you don't need constants but strings. What you want is to define your array keys as a string.
'key' => 'value'
Summary
Your echo should look like
$json = json_encode(array(
'ID' => $last_id,
'Title' => $title,
'Start' => $start,
'End' => $end,
'percentComplete' => $percentComplete
));
echo $json;
I have a cron job that runs a few mysqli queries and then stores the info in an array for later use. When the cron job runs, the mysqli queries return no syntax errors. I did a print_r of the result and it shows that there were multiple rows in the mysqli object but when the foreach loop ran, no info was extracted from the result object. The funny part? I run the same script in the browser to debug and everything works perfectly. Below is the code. (Browser PHP version 5.7, server/cron PHP version 5.3)
$mysqli = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$emailContent = array();
$result = $mysqli->query("SELECT * FROM emailType ORDER BY emailNumber");
print_r($result);
foreach($result as $row) {
print_r($row);
$emailNumber = $row['emailNumber'];
$email = array(
"emailName" => $row['emailName'],
"emailSlug" => $row['emailSlug'],
"emailDescription" => $row['emailDescription'],
"link" => $row['link'],
"subject" => $row['subject'],
"content1" => $row['content1'],
"content2" => $row['content2']
);
$emailContent[$emailNumber] = $email;
}
I included the return of the print_r methods from above. When running the cron, the print_r($result) returns this:
mysqli_result Object
(
[current_field] => 0
[field_count] => 16
[lengths] =>
[num_rows] => 8
[type] => 0
)
While the print_r($row) returns nothing. When running this through a browser I get the same info print_r($result) but I also get a mysql record for print_r($row). It is important to note that I get no error at all.
Extending my comments to the question here is a simple example to demonstrate how to correctly use that object you get returned, when running in query:
<?php
// ...
$result = $mysqli->query("SELECT * FROM emailType ORDER BY emailNumber");
print_r($result);
while($row = $result->fetch_assoc()) {
print_r($row);
// ...
}
What am I doing wrong here?
$adapter = new Adapter(array(
'driver' => 'Pdo_Firebird',
'database' => 'localhost:c:/firebird/mydb.fdb',
'username' => 'SYSDBA',
'password' => 'mypass'
));
$sql = 'SELECT * USERS';
$statement = $adapter->createStatement($sql);
$result = $statement->execute();
if I check $result->count() I always get zero (0). However I know this query should produce results.
I get no errors.
ok, so it appears I am actually getting a result, even though $result->count = 0.
So I have to add the following lines after my code above;
$resultSet = new ResultSet;
$resultSet->initialize($result);
foreach ($resultSet as $row)
{
echo $row->LOGIN . '<BR>';
}
Feels a little long winded. Is this the best way to do it? I presume I should add some check to see if any results where returned. But I can't see the correct way to perform this check.
Something really weird is going on here. I have this method for mysqli query.
public function select($options) {
$default = array (
'table' => '',
'fields' => '*',
'condition' => '2',
'order' => '1',
'limit' => 50
);
$options = array_merge($default,$options);
$query = "SELECT {$options['fields']} FROM {$options['table']} WHERE {$options['condition']} ORDER BY {$options['order']} LIMIT {$options['limit']}";
if ($result = $this->conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
} else {
printf("Query failed: %s\n", $mysqli->error);
exit;
}
}
Once the query get executed I get $rows and everything works like a charm. But then when I try to get specific key in array I get the "Query failed:" without specific message :S
$options = array(
'table' => 'settings',
'fields' => 'setting_wall_post,setting_status_tag,setting_photo,setting_like,setting_comment',
'limit' => '1',
'condition' => "setting_id = 6",
);
$check = $this->mysql->select($options);
print_r($check);
$check = $check[0];
if($check["setting_wall_post"]) //if I comment out this IF block it works :(
$this->scope["wall_post"] = "publish_stream";
Also I've tried to close mysqli connection and then I get
Warning: mysqli::query() [mysqli.query]: Couldn't fetch mysqli
this IF block is acting like it works with mysqli :S
So the question is, what is the issue here? Why can't I access to "setting_wall_post"? I guess that part is the problem since it works if I comment out that IF block.
Edit. What a silly I am, overlooked such a typo: $this->conn have to be used instead of undefined $mysqli.
That's why one should always have error reporting no less than E_ALL
The code you posted just cannot cause this kind of error.
Change your error reporting code to this one
} else {
throw new Exception($this->conn->error);
}
this way you will have a stack trace which will show the chain of calls, pointing to the place of code that caused particular error.
BTW, the whole function looks unusable and error prone to me. it is open to injection and require more code than a conventional SQL