Hi I have a problem with this method and it's driving me crazy.The query below should return one field from the database, an id where the filename is matched. Only one value should be returned. When I run the query I get an SQL object returned which looks fine:
mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 0 [type] => 0 )
However I cannot access the above query object no matter what way I try or at least I'm getting no value out of it. I did the exact same to get the package id and it works perfectly.
I used $row = $result_package_id->fetch_array(MYSQLI_ASSOC);
to get the package_id and I tried that for the module_id but it didn't work. Tried the mysqli_fetch_array and it doesn't work either. At a loss of what to do next can anyone help?
ADDED getPackageId method and if statement where the two methods are called. Every time a query is successful the id and package id are retrieved and a new object is created with the two values.
function getId($fileName){
$con = connect();
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR);
die('Could not connect: ' . mysqli_error($con));
}
$yModuleId = 0;
$sql_filename = mysqli_real_escape_string($con, $fileName);
$query_module_id = "SELECT id FROM y_module WHERE fileName='" . $sql_filename . "'";
$result_module_id = mysqli_query($con, $query_module_id);
while($row_model = mysqli_fetch_array($result_module_id)){
$yModuleId = $row_model['id'];
return $yModuleId;
}
}
function getYPackageId($package_name){
$con = connect();
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR);
die('Could not connect: ' . mysqli_error($con));
}
$sql_packageName = mysqli_real_escape_string($con, $package_name);
$query_package_id = "SELECT id FROM y_package WHERE name='" . $package_name . "'";
$result_package_id = mysqli_query($con, $query_package_id) or die("__LINE__ : " . mysqli_error($con));
while($row_package = mysqli_fetch_array($result_package_id)){
$yPackageId = $row_package['id'];
print_r($yPackageId);
print_r("</br>");
print_r("</br>");
return $yPackageId;
};
}
if($result_model && $result_package && $result_model_package) {
$yModuleId = getId($fileName);
$yPackageId = getYPackageId($package_name);
$yIdObject = new YIds($yModuleId, $yaPackageId);
$yIdObjects [] = $yIdObject;
mysqli_query($con, "COMMIT");
$message = array("success", "[SUCCESS]", "Model published successfully.",$module_id);
}
You can use
while ($row = $result->fetch_assoc()) {
$saved[] = $row;
}
but I think from your code displayed a more important issue is that you seem to be mixing procedural and object orientated SQL querying.
So:
1) Rewrite yourcode to use objects, your usage of mysqli_ functions only returns arrays.
2) or alternatively, use the current code as an array because that's what it is, not an object.
Procedural
function getId($fileName){
//this does nothing. Unless this is a custom function?
//$con = connect();
// should be:
$con = mysqli_connect(details,...);
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR); //?
die('Could not connect: ' . mysqli_error($con));
}
//$yModuleId = 0; //unneeded.
$sql_filename = mysqli_real_escape_string($con, $fileName);
$query_module_id = "SELECT id FROM y_module WHERE fileName='" . $sql_filename . "'";
//add an error feedback for debugging:
$result_module_id = mysqli_query($con, $query_module_id) or die("__LINE__.":".mysqli_error($con));
while($row_model = mysqli_fetch_array($result_module_id)){
$yModuleId = $row_model['id'];
return $yModuleId;
}
}
Object Orientated:
$query_module_id = "SELECT id FROM y_module WHERE fileName='?'";
$con = new mysqli($details,...);
$thisQuery = $con->prepare($query_module_id);
$thisQuery->bind_param("s",$sql_filename);
$thisQuery->execute();
while ($row = $thisQuery->fetch_assoc()) {
$saved[] = $row;
}
$thisQuery->close();
From this the $saved variable will be an array of results.
Additional notes:
You are using MySQL COMMIT near the bottom of your code and this is for transactions but you have not shown you've setup or begun any MySQL transactions.
You have a return inside a while statement in getYPackageId which means that the while wil only ever run once because as soon as it reaches the return it will do just that. Bad format.
Remove the semi-colon after the closing bracket of the while statement. This is bad syntax.
I figured out the problem and I feel like such an idiot! The problem was here
if($result_model && $result_package && $result_model_package) {
$yModuleId = getId($fileName);
$yPackageId = getYPackageId($package_name);
$yIdObject = new YIds($yModuleId, $yaPackageId);
$yIdObjects [] = $yIdObject;
mysqli_query($con, "COMMIT");
$message = array("success", "[SUCCESS]", "Model published successfully.",$module_id);
}
I was running the commit after I was trying to get the id and package_id from the database that's why I wasn't getting any results. I changed it to this:
if($result_model && $result_package && $result_model_package) {
mysqli_query($con, "COMMIT");
$yModuleId = getId($fileName);
$yPackageId = getYPackageId($package_name);
$yIdObject = new YIds($yModuleId, $yaPackageId);
$yIdObjects [] = $yIdObject;
$message = array("success", "[SUCCESS]", "Model published successfully.",$module_id);
}
It worked perfectly. This is how the getId() method looked when I got it working
function getId($moduleName, $moduleRevision){
$con = connect();
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR);
die('Could not connect: ' . mysqli_error($con));
}
$sql_moduleName = mysqli_real_escape_string($con, $moduleName);
$sql_moduleRevision = mysqli_real_escape_string($con, $moduleRevision);
$query_module_id = "SELECT id, module_name, module_revision FROM y_module";
$result_module_id = mysqli_query($con, $query_module_id);
while($row = mysqli_fetch_assoc($result_module_id)){
if($row['module_name'] === $moduleName && $row['module_revision'] == $moduleRevision){
return $row['id'];
}
}
}
Thanks to Martin for all the help and the advice much appreciated! Hope this can help someone by not making the same stupid mistake as me.
Related
Adapting an answer from here to try and pass an array as the parameter for a WHERE clause in MySQL. Syntax seems okay but I'm just getting null back form the corresponding JSON. I think understand what it is supposed to do, but not enough that I can work out where it could be going wrong. The code for the function is;
public function getTheseModulesById($moduleids) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_error());
}
// selecting database
mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());
$in = join(',', array_fill(0, count($moduleids), '?'));
$select = "SELECT * FROM modules WHERE id IN ($in)";
$statement = $con->prepare($select);
$statement->bind_param(str_repeat('i', count($moduleids)), ...$moduleids);
$statement->execute();
$result = $statement->get_result();
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
mysqli_close($con);
return $arr;
}
And the code outwith the function calling it looks like;
$id = $_POST['id'];
$player = $db->getPlayerDetails($id);
if ($player != false) {
$pid = $player["id"];
$moduleids = $db->getModulesByPlayerId($pid); //this one is okay
$modules = $db->getTheseModulesById($moduleids); //problem here
$response["player"]["id"] = $pid;
$response["player"]["fname"] = $player["fname"];
$response["player"]["sname"] = $player["sname"];
$response["modules"] = $modules;
echo json_encode($response);
[EDIT]
I should say, the moduleids are strings.
I am getting return values that do not exist in my current database. Even if i change my query the return array stays the same but missing values. How can this be what did i do wrong?
My MYSQL server version is 10.0.22 and this server gives me the correct result.
So the issue must be in PHP.
My code:
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Result:
array(1) {
[1]=> array(9) {
["UID"]=> string(1) "1"
["CreationTimestamp"]=> NULL
["UpdateTimestamp"]=> NULL
["ProcessState"]=> NULL
}
}
Solution:
I have found this code somewhere in my program. The program used the same name ass mine. This function turns the MYSQL result into a array. This happens between the result view and my script. This was done to make the result readable.
parent::processUpdatedAfter($date);
Function:
public function processUpdatedAfter($date)
{
$result = parent::processUpdatedAfter($date);
$array = Array();
if($result != false)
{
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$array[$row["UID"]]["UID"] = $row["UID"];
$array[$row["UID"]]["CreationTimestamp"] = $row["CreationTimestamp"];
$array[$row["UID"]]["UpdateTimestamp"] = $row["UpdateTimestamp"];
$array[$row["UID"]]["ProcessState"] = $row["ProcessState"];
}
return $array;
}
return false;
}
I edited this and my script works fine now thanks for all the help.
Note that, var_dump($result); will only return the resource not data.
You need to mysql_fetch_* for getting records.
Example with MYSQLi Object Oriented:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row['UID'];
}
}
else
{
echo "No record found";
}
$conn->close();
?>
Side Note: i suggest you to use mysqli_* or PDO because mysql_* is deprecated and closed in PHP 7.
You are var_dumping a database resource handle and not the data you queried
You must use some sort of fetching process to actually retrieve that data generated by your query.
$ts = '2016-09-20 08:56:43';
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > '$ts'";
$result = mysql_query($select_query, $link_identifier);
// did the query work or is there an error in it
if ( !$result ) {
// query failed, better look at the error message
echo mysql_error($link_identifier);
exit;
}
// test we have some results
echo 'Query Produced ' . mysql_num_rows($result) . '<br>';
// in a while loop if more than one row might be returned
while( $row = mysql_fetch_assoc($result) ) {
echo $row['UID'] . '<br>';
}
However I have to mention Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
$select_query = "SELECT `UID` FROM `process_state ` WHERE `UpdateTimestamp` > \"[given time]\" ORDER BY UID DESC ";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Try this hope it will works
I have this seriously strange issue. I have 4 tables in a FileMaker 12 file: Issues, Articles, FMBM, Ads. I have 2 methods in my results class, one writes a series of serial IDs to each of these tables, the other queries those tables. The method that writes the serial ID's works perfectly. The method that queries the tables works for 3 of the 4 tables (Articles, FMBM, Ads) but returns no result set for Issues.
I have checked permissions, but as this is the admin user, it has full access to all and there are no table specific or layout specific restrictions (again, it's the admin). Oddly enough, I thought maybe it's the query, but when I run "SELECT * FROM Issues" in my ODBC Query Tool, it returns the appropriate results. It's just baffling to me that the setKeys() method works perfectly but the view method ONLY fails on Issues.
The Model:
class Application_Model_Results {
public $keys;
public $odbc;
public $comp = array('Issues', 'Articles', 'Ads', 'FMBM');
public $existing = array();
function setKeys() {
$this->odbc = 'Migrator';
$obj = new Application_Model_Utilities();
$obj->name = $this->odbc;
$config = $obj->getElements();
$conn = odbc_connect($this->odbc, $config['user'], $config['password']);
if (!$conn) {
exit("Connection failed: -> " . $this->odbc);
}
foreach ($this->comp as $c) {
$sql = "SELECT Serial_ID FROM " . $c;
$rs = odbc_exec($conn, $sql);
if (!$rs) {
exit("Error in SQL");
}
while (odbc_fetch_row($rs)) {
$this->existing[] = odbc_result($rs, 'Serial_ID');
}
if (in_array(true, $this->keys[$c])) {
foreach ($this->keys[$c] as $v) {
if (!in_array($v, $this->existing)) {
$iSql = "INSERT INTO " . $c . "(Serial_ID) VALUES('$v')";
odbc_exec($conn, $iSql);
$obj->output = 'Inserted Serial_ID: ' . $v . ' into table ' . $c;
$obj->logger();
}
}
}
}
}
public function getResults($table) {
$this->odbc = 'Migrator';
$obj = new Application_Model_Utilities();
$obj->name = $this->odbc;
$config = $obj->getElements();
$conn = odbc_connect($this->odbc, $config['user'], $config['password']);
if (!$conn) {
exit("Connection failed: -> " . $this->odbc);
}
$sql = "SELECT * FROM " . $table;
$rs = odbc_exec($conn, $sql);
while (odbc_fetch_row($rs)) {
$results[odbc_result($rs, 'Serial_ID')] = odbc_fetch_array($rs);
}
return $results;
}
}
The Controller:
public function viewAction()
{
$results = new Application_Model_Results();
$result = $results->getResults('Issues');
$page = $this->_getParam('page', 1);
$paginator = Zend_Paginator::factory($result);
$paginator->setItemCountPerPage(1);
$paginator->setCurrentPageNumber($page);
$this->view->paginator = $paginator;
}
Note: If scrap the view code, and just write:
<?php
$conn = odbc_connect('Migrator', 'admin', '********');
$sql = "SELECT * FROM Issues";
$rs = odbc_exec($conn, $sql);
while(odbc_fetch_row($rs)){
print_r(odbc_result_all($rs));
}
I get no rows returned.
EDIT:
Culprit has been found:
while (odbc_fetch_row($rs)) {
$results[odbc_result($rs, 'Serial_ID')] = odbc_fetch_array($rs);
}
Now, I am working on a solution that grabs each result row and pushes it to an associative array, the problem is, on the view, I need to dump everything, not have to use odbc_result($rs, ) for every single field.
Finally, my nightmare is over:
public function getResults($table) {
$obj = new Application_Model_Utilities();
$obj->name = $this->odbc;
$config = $obj->getElements();
$conn = odbc_connect($this->odbc, $config['user'], $config['password']);
if (!$conn) {
exit("Connection failed: -> " . $this->odbc);
}
$sql = "SELECT * FROM " . $table;
$obj->output = 'Running query: ' . $sql;
$obj->logger();
$rs = odbc_exec($conn, $sql);
$obj->output = 'Results found: ' . odbc_num_rows($rs);
$obj->logger();
$results = array();
$i = 1;
while(odbc_fetch_row($rs)){
$results[] = odbc_fetch_array($rs, $i);
$i++;
}
return $results;
}
This returns an associative array that I can actually loop through.
NOTE: in this instance, any use of odbc_fetch_array, odbc_fetch_object, odbc_fetch_into, unless I forced the odbc_fetch_array to have a row value, would only reutrn every other result, not all results and then would die on the view unless I specifically called for a field value, and even then, the same value persisted across all paginated records.
my mysql table accepts NULL values on many fields, I'm updating records and my desktop app is creating a http string as follows and sending to a php script.
www.webpage/script.php?firstval=48.345345&secondval=234&thirdval=&fourthval=simon
on the db thirdval is already NULL
but the parameters in the http string may or may not hold values
do I need to :
A)pass the parameter in the http string as
b)pass the parameter in the httpstring as
c)cater for the null value in the php script(
d)not include the parameter in the http string at all
or something else
my phpscript is like so :
?php
DEFINE ('DBUSER', 'generic01');
DEFINE ('DBPW', 'genpass');
DEFINE ('DBHOST', 'mysql4.xxxxxxxxx.com');
DEFINE ('DBNAME', '_Places');
$dbc = mysqli_connect(DBHOST,DBUSER,DBPW);
if (!$dbc) {
die("Database connection failed: " . mysqli_error($dbc));
exit();
}
$dbs = mysqli_select_db($dbc, DBNAME);
if (!$dbs) {
die(" Database selection bit failed: " . mysqli_error($dbc));
exit();
}
$lat = mysqli_real_escape_string($dbc, $_GET['lat']);
$lng = mysqli_real_escape_string($dbc,$_GET['lng']);
$prox = mysqli_real_escape_string($dbc,$_GET['prox']);
$description = mysqli_real_escape_string($dbc,$_GET['description']);
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$direction = mysqli_real_escape_string($dbc,$_GET['direction']);
$avoiddays = mysqli_real_escape_string($dbc,$_GET['avoiddays']);
$validfrom = mysqli_real_escape_string($dbc,$_GET['validfrom']);
$validto = mysqli_real_escape_string($dbc,$_GET['validto']);
$gefid = mysqli_real_escape_string($dbc,$_GET['gefid']);
$expiry = mysqli_real_escape_string($dbc,$_GET['expiry']);
$query = "UPDATE places SET rt_lat = '$lat',rt_lng= '$lng',rt_prox = '$prox', rt_description = '$description', rt_direction = '$direction',rt_avoiddays = '$avoiddays',rt_validto = '$validto',rt_validfrom = '$validfrom',rt_gefid = '$gefid',rt_expiry='$expiry' WHERE rt_id = '$id'";
$result = mysqli_query($dbc, $query) or trigger_error("Query MySQL Error: " . mysqli_error($dbc));
mysqli_close($dbc);
?>
All help appreciated,
You do not need to include it in the http request, but you have to catch that, otherwise you get an E_NOTICE error.
For all fields that can be null:
if (isset($_GET['gefid'])) {
$gefid = mysqli_real_escape_string($dbc,$_GET['gefid']);
} else {
$gefid = null;
}
PHP has no knowledge of SQL nulls. If you want a blank/not-set $_GET value to become a null in the DB, then you have to take special steps:
if(isset($_GET['lat']) || ($_GET['lat'] == '')) {
$lat = 'NULL'; // a plain PHP string with the word "null" in it
} else {
$lat = "'" . mysqli_real_escape_string($dbc, $_GET['lat']) . "'"; // note the extra quotes
}
$sql = "INSERT ... VALUES ($lat, ....)"
If you do it any other way, e.g (just as an example, yes it's sql-injection vulnerable):
$sql = "INSERT ... VALUES ('$_GET[lat]', ...)";
Then for an empty $_GET['lat'] your query would actually be
INSERT ... VALUES ('', ...)
and you'd be inserting an empty string, NOT an sql null.
* The json_encode is returning NULL? is NOT the answer. I still receive a NULL when using the json_encode.*
I am very new to PHP, so if you could edit the section with the fixed code, I'd appreciate it.
This is my problem:
When an article under "introtext" contains non breaking lines, it returns NULL. The articles that do not have a non breaking space show up just fine.
This is my question:
How can I get the articles under "introtext" to display properly even if they contain a non breaking space.
Here's the code:
$connection = mysqli_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}else{
//Attempt to select the database
$dbconnect = mysqli_select_db($connection, $db);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}else{
$catID = $_GET['catid'];
$id = $_GET['id'];
$rtn = $_GET['rtn'];
if($id!=""){
$query = "SELECT * FROM tcp_content WHERE id=" . $id . "";
}else{
$query = "SELECT * FROM tcp_content WHERE catid=" . $catID . " ORDER BY publish_up DESC LIMIT " . $rtn . "";
}
$resultset = mysqli_query($connection,$query);
$records = array();
//Loop through all records and add them to array
while($r = mysqli_fetch_assoc($resultset))
{
$r['introtext'] = print_r($r['introtext'],true);
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
here are two links:
This link contains the non breaking space, so you'll notice introtext returns NULL
This link does NOT contain the non breaking space, so you'll notice the article shows
I found this link json_encode problem
see second answer. Charles is suggesting that use iconv() to remove URL encoded non-breaking space.
I finally figured it out and got it working
$r['introtext'] = utf8_encode($r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(160),' ',$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(147),'"',$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(148),'"',$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(146),"'",$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(145),"'",$r['introtext']);
$r['introtext'] = htmlentities($r['introtext'], ENT_QUOTES | ENT_IGNORE, "UTF-8");
$records = $r;