php: array: regex search not detected

Hello phpers!

I have a short PHP code not detecting a key word (eg. “PRI”) in a result set from a php:mysql query.
Would greatly appreciate some help … :wink:

Mysql Query return dataset is here that below PHP scripts returns.

mysql> show columns from PRODUCT_IMAGES;
+------------+-------------+------+-----+---------+----------------+
| Field      | Type        | Null | Key | Default | Extra          |
+------------+-------------+------+-----+---------+----------------+
| IMAGE_ID   | int(50)     | NO   | PRI | NULL    | auto_increment |
| BC_ID      | varchar(11) | YES  |     | NULL    |                |
| PHOTO_NAME | varchar(50) | NO   |     | NULL    |                |
| STATUS     | int(50)     | NO   |     | NULL    |                |
+------------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

The PHP code below is included in one or our websites as a template from a 3PA that is no-longer supported.

It’s supposed to detect that the above IMAGE_ID Column is the (PRI)mary key of the table and then “return $primary” . However, it seems to be not working. I’m new to php (after a couple of years plonking away at it) and i can’t decipher how this array() is being manipulate and why its not working, ie. it is not saying that $primary > 0…

I can easily handle this sort of thing in ksh/bash(awk/grep/sed etc), PL/SQL and SQL… etc but not in PHP. So any help would be greatly appreciated.

Thanks!
K


Some info about the calls and vars set in the following script:

database.php = handles the connect string to the database -- works fine for all our PHP pages.
$tbl  = is passed in (and confirmed) as PRODUCT_IMAGES

[php]

<?php require_once("database.php"); function get_primary($tbl) { global $Fields; $q1 = "show columns from `$tbl`"; $r1 = mysql_query($q1); while($ARR = mysql_fetch_array($r1)) { if ($ARR[3]== "PRI"&in_array($ARR[0],$Fields)) { $primary[] = $ARR[0] ; } } return $primary; } ?>

[/php]

I have tested the $result with the following query (removed the database.php to harcode the connection) here’s the code and results:

[php]

<?php //--- SCRIPT: test_cols.php $connect = mysql_connect('localhost', 'username', 'password'); mysql_select_db('DATABASENAME', $connect); $result= mysql_query("show columns from PRODUCT_IMAGES"); while ($row = mysql_fetch_assoc($result) ) { $Field = $row['Field']; $Type = $row['Type']; $Null = $row['Null']; $Key = $row['Key']; echo $Field."|"; echo $Type."|"; echo $Null."|"; echo $Key."|\n"; }; ?>

[/php]


Here’s the output:


$ php -f test_cols.php



IMAGE_ID|int(50)|NO|PRI|
BC_ID|varchar(11)|YES||
PHOTO_NAME|varchar(50)|NO||
STATUS|int(50)|NO||


$ 

I would first suggest you update to PDO or mysqli for database manipulation, I don’t even have those functions in the PHP version I am currently running.

Second, the bitwise comparison may be throwing you off, or are you looking to actually use regex for the comparison?

Your code is obsolete and has been completely removed from Php. As mentioned, you need to use PDO.

https://phpdelusions.net/pdo

Firstly, please let me extend our thanks to “astonecipher” and “Kevin Rubio” for you being so quick to reply and the help that you have provided.

I know my reply to your good selves is a bit long, i only have done this to reduce your time spent on it, and respect for your quick advice, that it so richly deserves !

Unfortunately, our Mysql/Domain provider does not support PDO at this stage, which i must say is rather disappointing!

Given this state of affairs, do you mind to spend a short while, to assist me with the current code in allowing me to confirm the output that is sent to “return $primary;”.

Please forgive me, as i said im only new to PHP after 2 years of plonking away at it. Specifically, are you able to insert a line or 2 please with the current code we have, that will enable me to “print” the array in its current form to text so that i can view what it is that the code is “seeing”.

For example, the 2nd code i wrote i can “see” the output and that “PRI” is in the output.

$ php -f test_cols.php
   
  IMAGE_ID|int(50)|NO|PRI|
  BC_ID|varchar(11)|YES||
  PHOTO_NAME|varchar(50)|NO||
  STATUS|int(50)|NO||

So from my basic understanding the below code is searching for “PRI” in the output.

I must confess I have looked here and many PHP manuals to try and “disambiguate” the original code but i just haven’t been able to.

[php]
while($ARR = mysql_fetch_array($r1))
{
if ($ARR[3]== “PRI”&in_array($ARR[0],$Fields))
{
$primary[] = $ARR[0] ;
}
[/php]

In ksh/bash i can use something like this to test for “PRI”. The sql_conn is just a bash function that emulates this:

#!/bin/ksh

function sql_conn(){
mysql -u username -pPassword database_name <<EOF
${1}
EOF
}

v_PRS=$(sql_conn "show columns from PRODUCT_IMAGES;" | grep 'PRI' | awk -F'|' '{print $2","$5}' | head -1)

$ if [ `echo $v_PRS | grep -c "PRI"` -gt 1 ] 
then
     export PRS=1
     export PRS_COL=$( echo $PRS | awk -F, '{print $1}')
else
    export PRS=0
    export PRS_COL=""
fi
   echo PRS_COL="${PRS_COL}"\
   echo PRS="${PRS}"

At the moment I “know” that “PRI” show be in the result set from:

[php]
mysql_fetch_array($r1))
[/php]

So i guess my question(s), and appreciation for any assistance, would be :

  1. Is there a an easier way to code the following so i can print/view the data that is being returned at r/time. ie. how can is see what this array is actually seeing? Is there a less “advanced” way of coding the below to accessing the same data?

if ($ARR[3]== “PRI”&in_array($ARR[0],$Fields))

  1. If i can’t output the array information, can i emulate the ksh/bash code in PHP so i can verify the query results?

Thanks again in advance for your help i really do appreciate it.

best regards
karl

First hurdle for us to cross is still the outdated code…

Unfortunately, our Mysql/Domain provider does not support PDO at this stage, which i must say is rather disappointing!
Need some splainin first! What version of PHP are you running? One it makes a difference with how we help. Two, PDO was native as of 5.1. SO, if your provider does not support that version of PHP you need to RUN SCREAMING to another host immediately!

To see what the array is returning you would use print_r( $array ) or var_dump( $array ). My preference is to do so like this:
[php]
echo ‘

’;
print_r( $array );
echo ‘
’;[/php]
Unfortunately, our Mysql/Domain provider does not support PDO at this stage

Give me a break! PDO has been available for ELEVEN YEARS now. If you are running Php that old you are just wasting your time and ours. Get another host immediately.

BIG Thanks to you “astonecipher” for the code I’ll give a try tomorrow I’m 13 hours ahead of you so sleep time. Really appreciate ur feedback I’ll tell domain.com that there service is FOS and they need to explain why their php 5.6.3 hosting does not support PDO.

Well Mr Kevin “Professional PHP helper” Rubio… Did u read the title page for this forum? Told you I’m a nubbie and all u do is tell me to stop waisting your time? Not appreciated really. Reporting u to moderator. Instead of just telling me to RTFM maybe could have addressed the issue? Ie. Printing the array data and not some sprout off about PDO.

I rarely ask forums for help only as a last resort.

BTW here’s why I posted here thinking I might try and ask for help.

Beginners - Learning PHP

A forum for beginning PHP programmers to ask questions. Please, no flames or put downs. There are no dumb questions only dumb answers and there probably are few truly dumb answers because they often lead to better ones.

Be fair now, I also said you are wasting your time as well.

telling me to RTFM
Um, yeah, I never said that so stop making things up. I gave you an EXCELLENT [u][b]TUTORIAL[/b][/u] link on how to use PDO.
maybe could have addressed the issue

I did address the issue. I said get a new host and stop using obsolete code. Until you do that anything else is pointless.

some sprout off about PDO

If you want to blow off the BEST advice that ANY experienced programmer would give you, then your own your own. The code you are using is so bad it has been COMPLETELY removed from php and will not work whatsoever in the latest version no matter what anybody does to it. NOBODY should be rightfully making it “work”.

Oh yea, I AM a moderator so I will consider myself reported for giving you the BEST and CORRECT advice. LOL!

“astonecipher”, your code worked great in dumping out the array(). That in turn lead me to more bread crumbs along the way that solved the problem. You know “teach a man to fish…” and all that is always the best option, rather than just “giving a man a fish”!

Thanks for your help again, I know i’ve said it before… but, your dedication to this forum and helping us with lesser skills makes a big difference in our worlds. It’s really great when you can ask for help and get such a rapid response, care in providing breadcrumbs and suggestions to get us along the road further. Now, after all the searching and trying so many things i think i finally am getting a handle on array() and how to access and search them.

I got some really good help/breadcrumbs/code snippets from the mods and admins @phpfreaks.com. They were really understanding of our problem with no access to PDO and also like your good self helped with the underlying issue with the function() construction. When we are out of contract with the domain host service will update to PDO which looks like it has some very cool options.

Thanks again to you and best wishes on your journey,
k

Well, captainK, PDO is built-into PHP, but, only if the PHP installation was installed as a default install.

If you customize the PHP install, you can leave it out. If your server hosting company did not install it, then, you don’t have it.
But, you need to at least move up to MySQLi … (The ’ i ’ stands for improved.) This update is simple and easy. Most of your
code will not need changing. You mostly just need to change each mysql_ functions to mysqli functions and include the
handle to your connection string. It is easy to make those changes and then you would at least be a bit more up to date.

You should also look into the “extract()” PHP function. In your next to last code in the original post, you will see where you
pulled data out of the query’s result and place them into strings of the same names. This can be done in one statement
using the extract function. Saves a lot of time. Here is an explaination of it:
http://www.w3schools.com/php/func_array_extract.asp
And, here is an explanation on how to use MySQLi…
http://www.w3schools.com/PHP/php_mysql_connect.asp
(Press the green Next-Chapter to walk thru the tutorial)

Hope this helps you…

This can be done in one statement using the extract function. Saves a lot of time.

Goodnes no Ernie! Now you have all these magic variables that appear out of nowhere. Same exact problem that was with register_globals and you know how that turned out. I used to used that method about 15 years ago until I learned better.

There are other issues as well. Search The Problem With ‘extract’

Well, what do you use in MySQLi instead of extract()? It would help if you explain why you don’t use extract anymore…

Just trying to give him some baby steps to get started with…

Thanks Ernie for you suggestions, greatly appreciated. I’ll check with our service provider about the mysqli. For now the script is working and our customer is now happy :slight_smile:

Others, If this thread doesn’t get deleted [or censored] here;s the solution that worked. I have left the --DEBUG-- in there so others might find useful for testing.

It’s not very “tricky” or advanced, but it now works. Marking topic as now “SOLVED”. :slight_smile:

[php]
//— primary.php

<?php require_once("database.php"); function get_primary($tbl) { $q1 = "SHOW INDEXES FROM `$tbl`"; //------DEBUG ---------------------------------------------- // print($q1. "\n"); //------DEBUG ---------------------------------------------- $r1 = mysql_query($q1); $rows = array( mysql_fetch_assoc($r1)) ; //------DEBUG ---------------------------------------------- // print_r($rows); //------DEBUG ---------------------------------------------- foreach ( $rows as $Array ) { if ($Array['Key_name'] == 'PRIMARY') { $primary[] = $Array['Column_name'] ; //------DEBUG ---------------------------------------------- // print_r($primary); // echo $Array['Key_name'], " is in the primary key\n"; // echo $Array['Column_name'], " is in the Column_name\n"; //------DEBUG ---------------------------------------------- }; return $primary; }; ?>

[/php]

ps. I do have a screen shot of my last post that “magically” was just deleted. Seems honest, and constructive feedback, and freedom of speech is not alive at phphelp.com.

This is not a freedom of speech forum. STAY ON TOPIC!

Glad you solved your problem. You can review your PHP settings and see what database systems are active on it by using
this command: phpinfo();

Just put it on a blank page, no html needed and save it on your server as a PHP file like info.php or whatever.
Then, go to it on your server and it will show you all of the currently active settings for your server’s PHP system.
You can review them and see if there is PDO on the system and the versions of MySQL that is active.

But, keep in mind that MySQL is no longer supported and is not even in PHP 7.0 and therefore your code will no longer work
if the server get’s its PHP up to date. Glad to hear it is working now…

Sponsor our Newsletter | Privacy Policy | Terms of Service