Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




Getting MySQL Generated Keys


I am a Java/JSP developer by trade but am currently developing a
MySQL/PHP solution.

In JSP when I run an INSERT statement on the db I am able to
automatically get back a list of any generated keys (without having to
do some sort of subsequent query to get the information).

Is there a PHP equivilent of this?




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Using Array_intersect() Without Keeyping Keys From The Array1, I.e. Re-number Intersect Array Keys.
I only use indexed arrays.

When I use array_intersect function, of $a3 = array_intersect( $a1,
$a2 ), I just need the vales of intersect array and let keys to be
re-numberred from 0.;

I found the intersect array $a3 have the correct values but keep the
keys of $a1. When I use
for loop from $index=0 to sizeof ($a3)-1, by $a3[$index], php reports
"undefined offset " problem.

How can I re-number the keys of $a3 from 0 to sizeof($a3)-1;



PHP MYSQL And Primary Keys
Say I have an ID field in my database that is a primary key and an UNSIGNED AUTO INCREMENTING TINYINT.

It stores range of 0-255. Ok I add a few items to the database, say 240. At a later date I delete a few records, say rows 33, 44, 55, 66, 77, and 240.

So the last record in the database now has an ID of 239, I add another record and it gets assigned an ID of 241?. I then add a few more and it finally reaches ID 255. Now all the ones I deleted previously do not exist. So I try to add another record, will it just get added and assigned the ID of a record that doesent exist such as 33, 44, 55, 66, 77 or 240? If not is there a way around this?

I am pretty new to MySQL and I dont know the answer to this but I know that it could prove to be pretty inefficient if an ID field can hold 255 records but only holds 240. Do you understand what I mean and can anyone answer my question?

Mysql: Get Foreign Keys
there is a function to get the foreign keys of a table?

i have this function to get all table infos:
$fields = mysql_list_fields($V['db']['name'],$table) or die
(mysql_error());
$columnsCount= mysql_num_fields($fields) or die (mysql_error());
for ($i = 0; $i < $columnsCount; $i++) {

$columns[$i]['name']=mysql_field_name($fields, $i) ;
$columns[$i]['length']=mysql_field_len($fields, $i) ;
$columns[$i]['type']=mysql_field_type($fields, $i) ;
$columns[$i]['flags']=mysql_field_flags($fields, $i);
}

but i need alo to know info about foreign keys.

Clearing A Table's Primary Keys In MySQL
This may be a silly question, but is there a way to clear out primary key's in a table so that the next entry starts over at 1 again?

We have a database that we have done a lot of testing in, and now that we want to go live we would like to have all the keys start at 1.

Do I have to drop and recreate all the tables or is there a way to do this via a command?

[ot] Listing Foreign Keys In MySQL On InnoDB
I use mysql 5 with innodb engine.
When I create a table like:
create table tbltest(
testid int(10) UNSIGNED NOT NULL auto_increment,
artid int(10) UNSIGNED NOT NULL REFERENCES tblart.artid,
PRIMARY KEY (testid)
) ENGINE=InnoDB;

Works fine.
If I insert a value in artid that doesn't exist in tblart, mysql produces an
error as it should do.

Now if I want to find out about the tablestructure, like this:
SHOW CREATE TABLE tbltest;
mysql just shows the create table syntax, BUT without the FK-constraint.

When looking through the documentation I only found SHOW TRIGGERS, but that
also doesn't list the FKs.

I must be missing something completely in the docs. :-/
How can I ask mysql which Foriegn Keys it has?

Generating Unique Primary Keys For MySQL With PHP (overkill)
I'm looking at some of my MySQL databases that rely on auto-incremented serial numbers for primary keys and I've decided it's time to come up with a better way as my projects are becoming increasingly complex.

I wouldn't want to be in the position of writing a solution that used up the 32,768 keys per month their SMALLINT serial number generator (just a guess) was producing and left thousands of customers stranded on Christmas day. [story]

I've put this function together that (as shown) has 3636 possible keys, or a little over 1.46 quindecillion. (It scales easily to smaller or longer keys.)

function produceFib($length) {
$val = ''
for($i=0;$i<$length;$i++) {
$str = 'abcdefghijklmnopqrstuvwxyz0123456789'
$shuffled = str_shuffle($str);
$val .= substr($shuffled, 0, 1);
}
return $val;
}
echo produceFib(36);

So here's my questions:
- Is this overkill?
- Do I need to do something more complex?
- How do you do it?

Forms Generated From Mysql Data
I can't figure out how to get PHP to tell me which boxes were checked and how I can use this information. PHP Code:

Inserting Link Into A Table Generated From MySQL
I'm trying to insert a link into a table that is generated through a MySQL Query. Here's the code:

Php Generated Form Array And Formatting For Mysql Query
As part of a form I have created I have a MySQL generated table who's fields include soccer team names, opponents, next match date, matchid etc. . Each row has a check box with the value of the checkbox being the unique row ID in the MySQL table (match id). When a user selects the teams from the list he would like more information about, the checkbox variable is parsed to the script as an array "$var[]".

If I use the following code, I can see all the contents of the $Var array that has been parsed to the script.

[php
<?
$number=count($var);
for($a=0;$a<=$number;$a++){
echo $var[$a];
}
?> /php]

The problem is how do I format the above output so that I can include it in a MySQL query statement? I have no way of knowing how many teams have been selected or the key index number for each variable in the array. How do I code this so that each row matchid is assigned it's own unique varable such as team 1, team2 etc?

I was thinking of using a loop to go through the array and generate $var appended with a number using the the PHP count() function. but seeing that I am fairly new to PHP I'm not sure if this will work or where to start!

Using Max() On Array Keys
i am using an array to store contact data within a session. it looks like this:

$_SESSION['contact'][$key][<content>]

$key counts the set of records, so i have

$_SESSION['contact'][&#390;']
$_SESSION['contact'][&#391;']
$_SESSION['contact'][&#392;']

and so forth. [<content>] stands for the fields containing the actual set of data, which are stored within the [$key]-arrays. at one point i need to find out what the highest value of $key is. running max($_SESSION['contact'])

simply leaves me with "Array()" as the result. what i am doing wrong, and how do i correct it?

Array Keys
is it possible to use only a key in an array meaning:

$arr["a"]="yo";
$arr["bc"]="ygo";
$arr["eea"]="wgyo";
$arr["fa"];
$arr["a"]="yo";

and then somehow get all the keys without and value i tried:

while (list ($key) = each ($arr)) {print $key;}

but i doens't seem to work.

Primary Keys
How is it that even though I have the column "username" in my database set
as a Primary key, using my PHP script to add new users to the database works
without any errors even when signing up using an existing username. I have a
database full of the same usernames!

Array Keys
If I used a "for each" to go through an array or irregularly numbed keys, is there a way to get the key number that the loop is currently on each time?

Shortcut Keys
I would be liek to be able to set up a webpage with shortcut keys so that when certain buttons are presses, a pop up window will open with a designated further page displayed.  Specifically I would like the shortcut keys to be a couple of the function keys, ie f10, f11 and f12. 

Array Keys
Been trying to figure out an array issue.  For some reason when I echo $key it's echoing "Array".  I want it to return the key (in this case adventure). Code:

PHP & MySQ + Unique Keys
I'm trying to write a system thats used for about 50 clients that uses html
forms and php to log details. The problem is that when a client loads the
form page it's given a value which is the last record in a table +1 (i.e. so
its the next record). The problem with that is that a client could sit on
that page for 20 mins (or whatever length of time) and a different client
could use that record number and there what be an error "duplicate key....".
I could use an MySQL UPDATE to lock the record when its issued to each
client and maybe use a timestamp and check if the timestamp is over 10 mins
and delete any records that are over 10mins but there is the possibility of
redundant data (or really useless data, a unique record and a timestamp) in
the table sitting there for 10mins at a time.

Is there an easy way of 'gauranteeing' a client a unique key? So you don't
have to lock the record when the page loads (this also means that when you
refresh the page that the unique key is incremented as you locked the last
record and didn't put anything into the table, so the refreshed page is
issued the next key +1 again).

Associative Arrays Keys
I have a some text that i have to sort according to their year. The text is in this format..

A Short Story (2000)
A long time ago (1999)
A list (2004)
Before Time (1999)
Car parts (2004)

so basically i want the output to be..

A long time ago (1999)
Before Time (1999)
A Short Story (2000)
A list (2004)
Car parts (2004)

I thought the way to go about this would be to extract the years and put the whole thing in an associative array with the years as keys, but of course the keys have to be unique so in this case values override each other. PHP Code:

Automatic Array Keys
My array keys are behaving strangely. In the manual it says calling an array like $array[] = "something" should make the value be put into the next available integer key available. However, my values are being placed with whole sets of blank keys inbetween. Here's what part of the print_r() of the array returns: Code:

ActiveRecord And Foreign Keys
I am having trouble wrapping my mind around the ActiveRecord pattern and
foreign keys.

I understand that for each table, there should be a class, and each row
is is effectively an instance.

But, my problem arises when I look at foreign keys and advanced
relationships. For basic foreign keys, I can just automatically
reference to the object. Example:

Table: invoice
id, notes

Table: items
id, cost, invoice_id

When working with an instance with items, I can easily load a new object
called "invoice."

But, what if I am already working with invoice, and I want to load
items? I can't think of any way to abstractly relate the two.

Also, what if I want to two things that are both a "has many"
relationship? For example, if I take users that can have multiple
qualities, I would need three tables: one for users, one for the
qualities, and one to link.

Table: users
id, username

Table: link
id, user_id, quality_id

table: qualities
id, quality_name

Foreach Is Returning Value Of First Key For All Keys
I'm having trouble with the foreach function. I'm using it twice
inside a user defined function with two different arrays, and in the
second instance it's returning the value of the first key for all the
keys. My code is shown below and the problem areas are marked with
comments. In case you're wondering, this script is for generating
sticky checkboxes that include an event handler.

<form>

<?php

if (! is_array($like)) { $like = array(); }

function make_checkbox_click ($name, $query, $options, $onClick) {
foreach ($options as $value => $label) {
printf('<label><input type="checkbox" name="%s[]" value="%s" ',
$name, $value);

# This is the instance of foreach that's not working correctly.
# It's returning the value of the first key for all the keys.

foreach ($onClick as $key => $event) {
printf ('onClick="%s" ', $event);
}

if (in_array($value, $query)) { echo "checked "; }
echo "/> $label</label><br />
";
}
}

# End of user defined function.

$characteristics = array(
'personality' => ' I love their personalities.',
'minds' => ' I admire their minds.',
);

# This is the array that foreach isn't working correctly with.

$charClick = array (
'personality' => "alert('Aren't they the greatest?');",
'minds' => "alert('They're smarter than most people their age.');",
);

make_checkbox_click (posPoints, $posPoints, $characteristics,
$charClick);

?>

</form>

Print Out Array Keys Only
Hi, there are lots of examples that show you how to print array values
given a key. Do you know how to print keys for a given array.

example

$myArray = array('a'=>1, 'b'=>2, 'c'=>3, 'd'=>4);

How do you print 'a', 'b', 'c','d' only without using any loops?

Printing Out Array Keys
i'm trying to find a simple way of printing out the keys in an array
generated by mysql_fetch_array which returns a single row.

i.e.

while ($row=mysql_fetch_array($result) )
{

print out the $row keys and values

}

is this possible?

How To Disable Controle Keys
In my application I want to disable my controle keys to
save copying and taking screen shots of the my page.

Write Array Keys To SQL
I have an array of data. I want to write each key in the array to its own row in SQL. what would be the best way to accomplish this?

Trouble With Moving Keys In An Array
OK i have the following array......

Associative Arrays: Are Keys Strings?
I am wondering if it is 'wrong' (although it works) to work with associative arrays like this:

$array[somekey] = blah

instead of specifying the key as a string:

$array["somekey"] = blah

What would you say? What is right, what is wrong from the point of view of correct PHP coding?

Foreach Loop With Array Keys
I am unable to get the following piece of code to work as
desired. The fields valuable seems to contain all values however the
vaules variable only contains the first assignied with

$values = ''' .
$arry[$keys[0]] . '''
$keys = array_keys($arry);
$fields = '`' . $keys[0] . '`'
$values = ''' . $arry[$keys[0]] . '''
foreach($keys as $key)
{
if($key != $keys[0]) {
$fields .= ', `' . $key . '`'
$vaules .= ', '' . $arry[$key] . '''
}
}

Prepend Array Keys With A String
I have looked on uk.php.net for the function I need but can't find it. Does anyone know what the function is called who's purpose is: to recurse through an array and assign values to keys whilst prepending the key name with a string specified by one of the function parameters?

Getting Data For Duplicate Keys In $_POST
I'm trying to process a form that I got from a JSP generated page.
Basically, want to take out and process some of the data, and redirect the
rest to a JSP page that will handle the rest. All works well, i traverse
$_POST, writeout hidden input fields and autosubmit the form with a little
javascript, a perfectly acceptable solution for our users.

However, the data the JSP page sends contains one certain input with the
same name a couple of times. Due to complicated reasons, I cannot change
that name into a PHP-style array. PHP, however, throws all the values of
those fields away except for the last one.

Is there any way to retreive data from inputs with duplicate names? I know
that with GET, I could just parse the query string myself, but sadly i need
to use $_POST (the thing I'm processing in PHP is a file upload). I have no
way of changing the input names themselves (and see no alternative other
than pulling a lot of ugly javascript hacks in the JSP page to fake it all).

Getting Deep Array Value Without Knowing Keys?
I've racked my brain for the last few hours trying to figure
this one out. I have an array of language strings such as :

$lang = array();
$lang['en']['prompt']['hello'] = 'hello'
$lang['en']['prompt']['bye'] = 'goodbye'
$lang['en']['number']['first'] = &#391;st'

This is being used by an ajax routine, so I don't know which string
will be requested at runtime. So, I've got $lang and a request
('en_prompt_hello'), and tried a few things such as:

$request = explode ($request);
$found_string = array_intersect_assoc ($lang, $request);

to no avail. Short of having to do a complicated recursion searching
at every available depth, is there an easy way to do this?

$_POST + Spaces And Dots In Keys
I have a very strange behaviour with POST keys.

Consider a test:

wtf.html:

=== Cut ===
<form action="eh.php" method="POST">
* * <input type="checkbox" name="many spaces and. . dots. . "/>
* * <input type="submit" value="Submit">
</form>
=== Cut ===

eh.php:

=== Cut ===
<?php
* * print_r($_POST);
?>
=== Cut ===

When we check the checkbox and click the Sumbit button we will see:

Array ( [many_spaces_and____dots____] => on )

It is send to server normally:

many+spaces+and.+.+dots.+.+=on

but in $_POST (or $HTTP_POST_VARS)

Multibyte Strings As Array Keys
Does this work? Something is breaking when I try to do this, and all I
can think of is that PHP does not allow multibyte array keys.

Sort An Array Using 2nd Dimension Keys
I need to sort an array (configured as shown) based on one of the second dimension keys.

[1] ['File_Name'] => test.doc;
[1] ['File_Type'] => MS Word;
[1]['Size'] => 50;
       
[2]['File_Name'] => test.pdf;
[2]['File_Type'] => Adobe PDF
[2]['Size'] => 150

[3]['File_Name'] => test.xls;
[4]['File_Type'] => MS Excel;
[5]['Size'] => 60;

For example, I'd like the order of the 1st dimension keys (integer indices) to reflect the order if the array is sorted by the "File_Type" key.

CLI- Reorder Array Keys After Using 'unset'
I'm having a problem finding a sort function that will reorder the keys in an array after I delete one of the array key/value pair. So if I have array: Code:

Foreign Keys Search Type
I have an sql db that I need to create a search page for.  I have used phpmyadmin to extract the entire table set up out.  The file it created is attached.

What i am trying to do is to create a search page that will retun the resutls of a search.  The only parameters that need to be searched are company, position or country.  Any or all of these can be search at the same time to produce a result.  Teh results need to be in a line by line format that when clicked on will show a second page with all teh details from the db.

Insert And Auto Incrementing Primary Keys
I am using MySQL and PHP. What I am trying to do is use a form to start a new record in a db. I am using an auto_incrementing field as my primary key. Right after I insert the record I want to get the value of the primary key so I can display a second form that will ask for more information. Is there a way to determine what the auto_incrementing field was set to after doing an insert?

Argument To Keys() Should Be An Array In Main.inc On Line 152
I am getting the following errors:

Warning: Argument to keys() should be an array in main.inc on line 152

Warning: Non array argument supplied for foreach() in main.inc on line 152


I've developed the site on my linux box at home using PHP 4.0.3pl1. It works great, but when I upload it to my hosting service I get the above messages. I've tried all the different ways to go through an associative array. I've tried doing an implode(array_keys($arr), ',') then split on ','. It keeps coming back to the fact that it doesn't recognize the array I declare right before it is an array.

The hosting service runs a BSD Bosx and uses PHP 4.0b2. I'm wondering if this was a problem with the second beta release or if it is something screwy between platforms.

Why does it work great on my box but when I upload it it craps out?

PHP Encrypt/Decrypt Whith Asymetrics Keys
I have generated two keys :
"C:>openssl req -nodes -new -x509 -keyout ben.key -out ben.crt -days
3650"
I try to encrypt/decrypt a string like "JOHN" with these asymetrics
keys. With the following code, it works.
I encrypt with the public key which is in the certificate.
I decrypt with the private key.
But why, the crypted message is different every time I start the
programm...?
__________________________________________________ _______
<?php
echo "---CRYPT---<BR>";
$source="JOHN";
echo "Message : $source<BR>";
$fp=fopen("./ben.crt","r");
$pub_key=fread ($fp,8192);
fclose($fp);
//echo $pub_key;
openssl_get_publickey($pub_key);
openssl_public_encrypt ($source,$sourcecrypt,$pub_key);
echo "Crypted message : ".$sourcecrypt."<BR><BR>";
$source="";

echo "---DECRYPT---<BR>";
echo "Crypted message : ".$sourcecrypt."<BR>";
$fp=fopen("./ben.key","r");
$priv_key=fread ($fp,8192);
fclose($fp);
$res=openssl_get_privatekey($priv_key);
openssl_private_decrypt ($sourcecrypt,$newsource,$res);
echo "Source decryptée : $newsource<BR><BR>";
?>
__________________________________________________ _________

Now here is my second question :
In fact I encrypt with a java programm where is my certificate and I
decrypt with a PHP programm like I've just explane before.

__________________________________________________ _________
public String crypt(String message) {

//Cert is in LDAP
Certificate cert =
userProvider.getUserCertificate(getCurrentUsername ());

PublicKey publicKey = cert.getPublicKey();

try{
Provider secProvider = Security.getProvider("BC");
if (secProvider == null) {
secProvider = new BouncyCastleProvider();
Security.addProvider(secProvider);
}
Cipher encryptCipher = Cipher.getInstance("RSA", secProvider);
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);

//Crypt...
String resultCrypt = new String();
byte[] messageBytes = message.getBytes();
byte[] resultCryptBytes = encryptCipher.doFinal(messageBytes);
resultCrypt = arr2str(resultCryptBytes);

return resultCrypt ;

}catch(Exception e){
//throw ...
}
}
__________________________________________________ ______________

Why my programm PHP can't decrypt the message? I use evidently the
correct private key which corresponds with the public key.

Explicit Numeric Keys Vs Item Position
Say if I have a mixed array:

$array = array("item1", "2"=>"item2", "5", "item4key"=>"item4")

Is it possible while looping through the array (foreach ($array as
$key=>$val)) to check if an item has an explicit key specified instead
of its automatically assigned position key?

One Result Set Makes Two Lists With Same Keys And Values
I have a page with two drop-downs, each listing the same employee names
and their id's as the values. So they look like:
<select name="selection_1">
<option value="12">Curly</option>
<option value="8">Larry</option>
<option value="36">Moe</option>
</select>

....then further down the page:

<select name="selection_2">
<option value="12">Curly</option>
<option value="8">Larry</option>
<option value="36">Moe</option>
</select>

Currently I am doing this, which works but seems sloppy:

<select name="selection_1">
<?
while($employees=mysql_fetch_assoc($qry_rslt)) {
/* ADD NAMES TO DROPDOWN WITH emp_id's AS THEIR VALUES */
?><option
value="<?=$employees['emp_id']?>"><?=$employees['name']?></option><?

/* CREATE ANOTHER ARRAY WITH THE emp_id AS THE KEY */
$emp_list_2[$employees['emp_id']]=$employees['name'];
}
?>
</select>

Then on the second drop-down:

<select name="selection_2">
<?
foreach($emp_list_2 as $key => $emps) {
?>
<option value="<?=$key?>"><?=$emps?></option>
<?
}
?>
</select>

Using Keys And Sessions To Bypass Secure Directory
I have a Pay Pal "buy now" button on my website, when the customer goes to Pay Pal to make a payment, they are then redirected to a certain page on my site. I have secured the my directory so that no one can just type in the URL?

I do however, want the customer to be able to bypass that secure login when they are redirected from Pay Pal.  I know I can use keys and sessions to pass the username and password but I'm unclear on how this works. 

Manipulate Array Keys And Values For Query String
i'm creating a function where I can update my records ... but it doesnt work...I echoed my SQL query and it turned fine..but it didnt update my record! PHP Code:

Getting Keys/values From POST Array In An Orderly Fashion..
I've got this javascript that results in the following being posted;

weight_1 = 30
cost_1 = 20
amount_1 = 32

weight_3 = 65
cost_3 = 23
amount_3 = 12

weight_7 = 43
cost_7 = 9
amount_7 = 12

etc.., with the numbers appended to the keys (here 1, 3, and 7) ascending but not sequential.

I need my PHP recieving these POST keys/values to present them like this:

#1
Weight: 30  Cost: 20  Amount: 30

#2
Weight: 65  Cost: 23  Amount: 12

#1
Weight: 43  Cost: 9  Amount: 12

Whats' the right way to do this?
I've been messing around with array functions but haven't quite figured out which to use..

Php Script Generated By Php
I am trying generate a new PHP file from an existing page using PHP. Currently I'm using the output buffer to capture content destined for the page, and then am capturing that output and writing to a file.

The problem I am having is that all PHP scripts within the new page content are executed and the results are written to the new file, when I would like the PHP code itself to be written to the new file, unprocessed.

So now I am trying to just store the new page as a string and bypass the use of the output buffer, but do not know how to store php code within a string without having it execute...

Using Php Generated Pictures With HTML?
I am able to create images with the use of the GDLIB.
but I am not able to use these images together with HTML. I always get the
message "headers are already sent.

I Am Trying To Pipe In Some Auto-generated PHP Into Php.exe
I am trying to pipe in some auto-generated PHP into php.exe, to no
avail:

How To Farmat Php-generated Table
the font size declaration seems to be ignored. Is it possible to set format for
tables generated with php?

<?php

echo "<table border=1 font size=8>";
echo '<tr><th font size=8>Date</th>
<th>IP Address</th>
<th>Operating System</th>
<th>Browser</th>
<th>Referring Page</th>
<tr>'

?>

Php-generated Png Transparency Issue In IE
I've been trying to get my page, which works perfectly in Firefox, to work in IE as well. one problem was getting the .png images to display properly, which was fixed by doing this:

filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='imagename.png')

but what of php-generated .png files? putting the php file as the src doesn't work. the php-generated images don't work at all in IE (but work fine in firefox).

(the php-generated image uses a transparent color made with imagecolorallocatealpha. when I just use imagecolorallocate it shows up, but is not transparent as I want it.)

Generated PHP Web Database Forms
I'm still gaining experiance in developing PHP applications, and have completed
a couple of projects already.

This has prompted me to look for ways to reduce the development time for web
enabled database applications. Every web database has basic operations such as
add,delete,update and search. I have been creating HTML forms and processing
the results with php code. I have managed to reduce the number of forms required
by using the smarty template engine.

I want to go a stage further and be able to produce the forms and the processing
code purely by looking at some sort of schema file , or using
"mysql_list_fields()" and "mysql_list_dbs()".

Before I start my quest of many late nights of coding. Can any of you guys
give me a head start by pointing me at a solution/hint.




Copyright © 2005-08 www.BigResource.com, All rights reserved