Array not storing entire string (seemingly) - php

Why is the following code failing to store the entire strings from the "name" column into my output array? The code did work at some point.
$contacts = "";
$sql = "SELECT * FROM s_issue.t_contact WHERE orgid='$orgid' ORDER BY id";
$results = db_query($db, $sql, "psql");
while($row = pg_fetch_assoc($results)){
$contacts[$row["id"]] = $row["name"];
}
return $contacts;
The database column id contains integers, and the name column contains strings. The expected output was a list of contact names, but in my initial trials, I was getting a blank list.
I was asked to look at some very old legacy code. It was non-obvious as to the recency of the upgrade to PHP7, and when I started looking I wasn't even sure it was PHP7.

In case you come across some legacy code like this, and find yourself wondering why the output array does not contain what you expect, have you recently upgraded to PHP7? Because that's the cause.
The initial line in PHP7 now coercively (default) types $contacts as a string. Further, a string can be indexed numerically to access each character in that string. That is:
$foo = "abcde";
echo $foo[1]; // outputs 'b'
So when $row["id"] is numeric, then $contacts[$row["id"]] becomes a string with a numeric index. Hence, only one character can be stored at that location, and it is the first character of the string $row["name"].
The proper fix is to either remove the wrongly-typed initialization line of $contacts = "" completely, or correctly initialize it to the type actually desired, an array:
$contacts = array();
The code in question worked fine before PHP7. It will fail in mysterious ways in PHP7.

Related

How to assign specific dbs value to multiple variables without using multiple query statements?

I'm currently creating an Admin Panel and I'm coding it to be 100% fool proof. You'll be able to edit every piece of information through editing phrases from the database.
The main way I know is to use this:
$c = $conn->query('SELECT phrase FROM phrases WHERE phrase_name = "corp_name"') or trigger_error($conn->error);
$d = $c->fetch_array();
$phrase_corp_name = $d['phrase']; // "Corporation"
This is not very ideal when I'm going to have dozens of phrases.
The issue is, when I try to select a phrase like so, it does nothing:
$phrase_corp_name = mysqli_query($conn, "SELECT phrase FROM phrases WHERE phrase_name = 'corp_name'");
This should ideally output, "Corporation," which is the value of "phrase" in this instance. I'm assuming the code is wrong, but I can't wrap my head around it.
The error I get here is:
Recoverable fatal error: Object of class mysqli_result could not be converted to string in ... on line 94
A single variable for a single row in the database is completely unnecessary. You can use associative arrays for this purpose; they are perfect for such task.
Get all the results from your phrases table into an array and then access the phrases using keys.
$c = $conn->query('SELECT phrase_name, phrase FROM phrases') or trigger_error($conn->error);
$phrases = [];
foreach ($c as $row) {
$phrases[$row['phrase_name']] = $row['phrase'];
}
and then access the values like this:
echo $phrases['corp_name'];
As a side note, you would be better off enabling mysqli error reporting, rather than doing it manually yourself. Please read How to get the error message in MySQLi?

PHP not recognizing string as name in variable function

I have written a function that is supposed to be able to generate a number of input fields which will be commonly used in a private web application.
Details of these fields are stored in the mysql database. There is a varchar field which holds the name of the function that generates the related text for a dropdown, as well as the associative key to retrieve the right string from the function's result.
The variable function name does not call the function. It worked in an earlier simplified iteration using only mysqli_fetch_row rather than mysqli_fetch_assoc.
I'd like to get it working with associative keys. (I can see no reason why associative keys could be the problem).
I've tried various forms of eval and exec. I can get a lite version to work with mysqli_fetch_row.
I have followed instructions here: Store function name in database and then execute it
I haven't been able to find anything else that directly adresses the problem.
$funcResult = $func($fldNmValue)[$funcKey];
doesnt't work
$funcResult = rank($fldNmValue)[$funcKey];
works
'rank' is one of the function names in the database
it is pulled from the database by:
$query = "SELECT fieldFunction,fieldFunctionKey FROM fieldType WHERE fieldTypeId='$fldTypeId'";
$result = db_query($query);
$data = db_fetch_assoc($result);
$func = $data['fieldFunction'];
I have verified that $func contains valid function names like 'rank' or 'castDetails'.
printing "$func($fldNmValue)" gives, for example:
castDetails(2)
as expected.
PHP refuses to execute $funcResult = $func($fldNmValue)[$funcKey]; and simply exits.
I had expected it to function like it did when using mysqli_fetch_rows.

Wordpress $wpdb->get_results(...) issues with comparing strings

I am trying to iterate through the rows in a phpbb table called phpbb_posts and extract each entry in phpbb's "post_subject" column and compare its value with a predefined string in Wordpress PHP file but I am having some issues - the expressions don't evaluate to true.
My phpBB's tables are installed in WP's database so I have full access to the values.
See the code below to demonstrate the issue I am having.
function matchPhpBBTopic()
{
global $wpdb;
$wp_post_title_string = get_the_title();
$result = $wpdb->get_results("SELECT * FROM phpbb_posts");
foreach($result as $row)
{
$phpbb_post_title_array = array($row->post_subject);
$phpbb_post_title_string = implode("", $phpbb_post_title_array);
// One of the values in $row->post_subject contains
// the value in $wp_post_title_string
if (strcmp($wp_post_title_string, $phpbb_post_title_string) == 0)
{
// This line never runs but the $wp_post_title_string value
// is there, in the table, I've printed it and it's there
echo 'We found a match!<br>';
}
}
}
Any assistance would be appreciated.
So in other words, I have a topic posted in WP and I have exactly the same topic posted in phpBB and I want to iterate through the phpBB's table and when I find the topic, I want to run some code. I don't understand why the "if" expression does not run.
Couldn't you just do:
if ($wp_post_title_string == $phpbb_post_title_string) {}
I don't think strcmp() is appropriate. It converts the string to encoding numbers.
http://us1.php.net/strcmp
Also check for lower and upper case, spaces, and different encodings.
Do strtolower() and trim() first and see what you get.
Also looks like you're imploding subject and title, so don't think they'll match.

Get Data from Array by Variable

I have this array:
$array = array();
$array['123'] = 'abc';
$array['456'] = 'def';
Now I would like to get data from that array based on a variable. This is what I tried:
$variable = '123';
$result = $array[$variable];
echo $result;
It appears to be wrong, but i don't know why. It results in a warning:
Illegal offset type […]
I ran that exact code into my compiler and it worked; possibly it is a white-space error (random characters you cant see but still cause bugs). I would try to physically retype that section of code and delete the old one.
I would suggest trying this to make sure the variable is cast as a string:
$result = $array[(string)$variable];
That's most likely your problem. I think maybe $post['id'] is either mistakenly a multi-dimensional array or somehow becoming an object of a type not accepted as an array key.

An imported array from mysql works, but the array can't be used by php as an array?

The code below won't work because of this line $params=array($data);. It needs something other than $data. Or it needs something to happen with $data prior to this line.
If the line is written as $params=array("A", "B", "C", "D"); then it works great, but my array is in the $data variable, not written out like that. If there is a way to get the array converted to being written out like that, that would work too.
The end result should show every possible combination (not permutation) of the contents of the array. Like in the example above it shows ABC, BD, etc.
$data = mysql_query('SELECT weight FROM my_table WHERE session_id = "' . session_id() . '"');
$params=array($data);
$combinations=getCombinations($params);
function getCombinations($array)
{
$length=sizeof($array);
$combocount=pow(2,$length);
for ($i=1; $i<$combocount; $i++)
{
$binary = str_pad(decbin($i), $length, "0", STR_PAD_LEFT);
$combination='';
for($j=0;$j<$length;$j++)
{
if($binary[$j]=="1")
$combination.=$array[$j];
}
$combinationsarray[]=$combination;
echo $combination."<br>";
}
return $combinationsarray;
}
mysql_query() only returns a result resource ID. To retrieve data, you must use one of the "fetch" commands, for example
$params = array();
while ($row = mysql_fetch_assoc($data)) {
$params[] = $row['weight'];
}
Also, your query is possibly vulnerable to SQL injection. I wouldn't implicitly trust the value from session_id(). I'm not entirely sure of this but it may simply retrieve the value from the session cookie.
At the very least, sanitise the value with mysql_real_escape_string(). A more robust solution which would bring your code out of the dark ages would be to use PDO and parameter binding.
$data is not an array. Assuming mysql_query() did not return an error or an empty result (both of which you should check for, by the way--lookup documentation for mysql_error() and mysql_num_rows() perhaps, maybe some others), $data is a resource.
So you want $params=mysql_fetch_array($data) to make it an array. (That assumes that there is only one result. If it might return more than one row, you'll probably want to wrap it in a loop. If you are 100% certain that session_id is unique , then you can get away without the loop, I suppose. You can also get away without the loop if you only care about the first result in a multi-row result, although I'd throw in a LIMIT 1 in your query in that case to improve performance.)
There are lots of options (do you want a numerically indexed array, or one where they keys are the names of the columns, etc.) so read up at http://www.php.net/manual/en/function.mysql-fetch-array.php.
Ok there are alot of fundamental problems with your script. I personally recommend to first read this article and then about the actual function called mysql_fetch_array().
Simply put, what you are receiving from mysql is resource (corrent me if i'm wrong!) and you have to fetch array on that.
$params = mysql_fetch_array($data);
PS: This makes no sense: $params=array($data);

Categories