Sunday, 15 March 2015

mysql - PHP function loop to check DB for existing string -



mysql - PHP function loop to check DB for existing string -

i trying create php function check against mysql db if value has been randomly created exists, if repeat until makes value in not exist.

currently have failed miserably, although in precedence believed method have worked, not.

the php

i tried in script on own , realised php functions not run unless called.

conn(); //db connection function genid() { $newidref = uuaig(10); $querycheck = "select * contentarticle_vids videoarticle_id = '$newidref' "; $resultcheck = mysql_query($querycheck); $numrows = mysql_num_rows($resultcheck); if ($numrows !== 0) { genid(); die(); } }

so.. tried this, of made unhappy (broke whole page).

conn(); //db connection genid(); function genid() { $newidref = uuaig(10); $querycheck = "select * contentarticle_vids videoarticle_id = '$newidref' "; $resultcheck = mysql_query($querycheck); $numrows = mysql_num_rows($resultcheck); if ($numrows !== 0) { genid(); die(); } if ($numrows === 0) { homecoming $newidref; die(); } }

for reference random string generator uuaig(10).

i need random string generated , returned if string confirmed non existent in database.

how proceed?

why create select @ all? set unique index on videoarticle_id. when seek generate , insert new id, handle insert failure , retry new id.

if have code scheme generating id's , expect few id collisions, way more efficient.

so function might like:

function genid() { $idsuccess = false; $max_retries = 3; $i = 1; while (false === $idsuccess && $i <= $max_retries) { $newidref = uuaig(10); $querycheck = "insert contentarticle_vids (`videoarticle_id`) values ('$newidref')"; $idsuccess = mysql_query($querycheck); $i++; } if(false === $idsuccess) { error_log('could not generate id in genid()'); homecoming false; } homecoming $newidref; }

note have added max retry limit don't have infinite loop possibility. also, note go ahead , reserve spot new unique id in db table.

finally, obligatory note using deprecated mysql extension. should not writing new code using extension.

php mysql function loops

No comments:

Post a Comment