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;
Related
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'],
];
}
I have the following code in some php:
$stmt = $connection->prepare("SELECT * FROM users where email = ?");
$stmt->bind_param('s', $email);
if($stmt->execute()){
$result = $stmt->get_result();
$isUserFound = $result->num_rows == 1;
if(isUserFound){
$row = $result->fetch_row();
echo "<br>id: " . $row["id"];
}
I know that the user is found because the code inside the second if executes and I have done a manual check also to make sure. Is there something wrong with the syntax I have used? The echo returns just "id: " with no id from the database even though the user exists.
I have tried using single quotes for the id and also tried in capital letters, all return nothing.
According to the documentation, fetch_row() is used to "get a result row as an enumerated array." This will result in an array like this:
$row = [
0 => "2342",
1 => "user#example.com",
2 => "User",
];
Instead use fetch_assoc() which will "fetch a result row as an associative array" and give you something like this:
$row = [
"id" => "2342",
"email" => "user#example.com",
"name" => "User",
];
Note that if you enabled some error reporting in your development environment you would have seen "undefined index" notices that might have helped you solve this issue.
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
I'm using MySQLi for a project (but could easily switch to PDO, read the edit at the bottom). What I want is to be able to process an associative array into an mysql query without typing every key/value pair manually. I know that might be simply put, but I'm still in a learning process when it comes to MySQLi/PDO. To make it clear what I mean here is an example:
Let's say I have this associative array:
$data = array(
'name' => 'Objective',
'short_name' => 'OB',
'generation' => 1
);
What I want is to create a query like this:
UPDATE signals SET ? = ? WHERE sid = '1'
And it to become a query like this (or instead of an UPDATE, an INSERT, SELECT etc.):
UPDATE signals SET
name = 'Objective',
short_name = 'OB',
generation = 1
WHERE sid = '1'
So basically my question is: is this possible with MySQLi or PDO itself? If it's possible how would I have to do this?
I've read on preparing statements before executing, but it's not getting to me yet. Hopefully someone can help me out.
Edit: I'm still very early into the project so i'm also fine with using PDO, but the same question remains. I did look into both PDO and mysqli, and I'm not sure how to do it with PDO either. So for the sake of the question i'll add PDO to as a tag and to the question.
Here is a function that will take an input array and produce something you can drop straight into your query, as long as you are only updating a single table:
function array_to_pdo_params($array) {
$temp = array();
foreach (array_keys($array) as $name) {
$temp[] = "`$name` = ?";
}
return implode(', ', $temp);
}
Now you can perform your PDO query like this:
// The data
$data = array(
'name' => 'Objective',
'short_name' => 'OB',
'generation' => 1
);
// The parameter for the WHERE clause
$sid = 1;
// Build the query string
$query = "
UPDATE `signals`
SET ".array_to_pdo_params($data)."
WHERE `sid` = ?
";
// Convert the data array to indexed and append the WHERE parameter(s) to it
$queryData = array_values($data);
$queryData[] = $sid;
$stmt = $db->prepare($query); // Obviously add the appropriate error handling
$stmt->execute($queryData);
You can use the PDO's execute statement by passing an array of input values, for a prepared query. For reference: http://php.net/manual/en/pdostatement.execute.php
Example:
<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->execute(array(':calories' => $calories, ':colour' => $colour));
?>
Zend_DB will let you do exactly that.
Tho we created a wrapper over it my work to make it simpler, I really think it's as simple as you can get, and it does all the magical stuff for you.
You really should give it a try; big time saver once you learn it.
How about building the query with http_build_query as follows:
$columns = array(
'name',
'short_name',
'generation', ...
);
$data = array(
'name' => 'Objective',
'short_name' => 'OB',
'generation' => 1
);
$to_update = array_intersect_key($data, array_flip($columns));
$update_string = urldecode(http_build_query(array_combine(array_keys($columns), array_fill(0, count($columns), '?')), '', ', '));
try {
$stmt = $db->prepare(sprintf('UPDATE table SET %s WHERE condition=?', $update_string));
$result = $stmt->execute(array_values($data));
...
} catch (\PDOException $ex) {
}
Be sure to have the parameter for the WHERE condition at the end of your $data array.
Having a repetitive code like so:
$SQL = " INSERT INTO ... ";
mysql_query($SQL, $conexion);
$error = mysql_error();
if($_ADM['id_user']==1) {
if( ! empty($error)) {
$debug = array(
'message' => "SQL Error in news_edit module.",
'line' => '177',
'error' => $error,
'SQL' => $SQL
);
exit(print_r($debug));
}
}
This is a common code, that repeats its self every time $SQL changes. What I'm trying to achieve is a way to debug if any error occurs and as I you can see, I have the line parameter which contains the number line where last mysql_query was executed, but I have to type that manually and every time I add code before it, the line parameters needs to be changed with the new line value.
Is there any way of identifying where was last time mysql_query executed? Any other way of improving the code above?
try using
'line'=> __LINE__,
its a magic constant which displays the current line of the file..
I think what you want is debug_backtrace function.
Check the manual for specs:
http://php.net/manual/en/function.debug-backtrace.php