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
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'],
];
}
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;
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.
Wonder if you can help me figure this out. Latest PHP in WordPress 3.92. WordPress is using MySqli. I am trying to change my custom MYSQL to MYSQLI which should really be simple enough, but is throwing up so issues.
Below are 2 examples. Example 1 is using WordPress built in MYSQLI connection inside a function and the one underneath is my own. The first one throws up errors as shown but my own one does not.
function name{
global $wpdb;
$options = array();
$res=mysqli_query($wpdb,"select ID,County from counties ORDER BY County ASC");
$value="";
$label="Please select a county";
$options[] = array('label' => $label, 'value' => $value);
while($row=mysqli_fetch_array($res)) {
$sC=$row['ID'];
$res1=mysqli_query($wpdb,"select County from wedding_shows where County='$sC'");
if (mysqli_num_rows($res1) == 0) {
} else {
$options[] = array('label' => $row['County'], 'value' => $row['ID']);
}
}
}
Here are the errors i get
Warning: mysqli_query() expects parameter 1 to be mysqli, object given eval()’d code on line 3
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given eval()’d code on line 4
and here is it working with my own connection and no errors.
function name(
$dbhost1 = 'localhost';
$dbuser1 = 'user';
$dbpass1 = 'pass';
$dbname1 = 'DBName';
$conn=mysqli_connect($dbhost1 ,$dbuser1,$dbpass1,$dbname1);
$options = array();
$res=mysqli_query($conn,"select ID,County from counties ORDER BY County ASC");
$value="";
$label="Please select a county";
$options[] = array('label' => $label, 'value' => $value);
while($row=mysqli_fetch_array($res)) {
$sC=$row['ID'];
$res1=mysqli_query($conn,"select County from wedding_shows where County='$sC'");
if (mysqli_num_rows($res1) == 0) {
} else {
$options[] = array('label' => $row['County'], 'value' => $row['ID']);
}
}
}
I must be looking to hard as I cannot see why this would not work in the first instance to save having to create a new connection inside every function.
Many thanks
P
The first argument of mysqli_query is expected to be a mysqli connection object. $wpdb is not a mysqli connection object, it is the wordpress database object. That being said, you could just do $wpdb->get_results("select ID,County from counties ORDER BY County ASC"); instead, given that the query is proper.
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