PHP Repeat a func when variable doesn't meet requirement - php

I'm newbie at PHP (I'm learning it) so could someone help me to fix my script?
$total = mysql_num_rows(mysql_query("SELECT * FROM files;"));
$rand = rand(0,$total);
$check = mysql_num_rows(mysql_query("SELECT * FROM files WHERE id=".$rand.";"));
do {
$rand;
}
while($check < 1);
I write this code to get a random column ID from MySQL ( I tried "ORDER BY RAND()" but it's too slow), When this ID doesnt exist in MySQL's table it will repeat this job until it find a exist ID with this way:
$check = mysql_num_rows(mysql_query("SELECT * FROM files WHERE id=".$rand.";"));
But I think I was wrong in coding it. Please help me to fix. Thanks.

You'll need to place the query inside the loop otherwise it won't actually check again. See below:
$total = mysql_num_rows(mysql_query("SELECT MAX(id) FROM files;"));
$check = 0;
do {
$rand = rand(0,$total);
$check = mysql_num_rows(mysql_query("SELECT * FROM files WHERE id=".$rand.";"));
}
while($check < 1);

Is it ok?
do {
$rand = rand(0,$total);
}
while(mysql_num_rows(mysql_query("SELECT * FROM files WHERE id=".$rand.";")) < 1);

Related

Updating a row number which has been randomised

So I currently have a random number being generated in PHP and I want to know how I go about updating the row number in my selected table. Code below:
$sxiq = mysql_query("SELECT * FROM `starting_eleven` WHERE `team_id`=$uid");
$sxir = mysql_fetch_row($sxiq);
$first = rand(1,11);
$stat_changed = rand(11,31);
$up_or_down = rand(1,2);
if ($up_or_down == 1) {
$player_name = explode(" ", $sxir[$first]);
$fn = $player_name[0];
$ln = $player_name[1];
$statq = mysql_query("SELECT * FROM `players` WHERE `first_name`=$fn AND `last_name`=$ln AND `user_id`=".$_SESSION['user_id']);
$statr = mysql_fetch_row($statq);
$stat = $statr[0];
}
I would like to update the row $stat_changed from the database, but I'm not sure if this is possible without doing a long if statement, telling the code if $stat_changed = 13 $stat = pace or something along those lines, but if this is the way it must be done then I'll have to. Just thought I'd see if there was any other simpler ways of doing this.
Thanks in advance
if ($stat_changed == 13) {
//insert UPDATE statement here
}

selecting in php WHERE x = $array[index]?

I've tried searching for answers to my problem but no one else seems to have had this problem! I'm basically trying to select in php using the WHERE statement, I want to compare my $ID to variables stores in an array called $resultAddID2. This array has values [1,2,1]; if I try accessing $resultAddID2[0] it works fine, but if I try to do it with $resultAddID2[1] or $resultAddID2[2] it doesn't work at all! I'm sure this is something silly but for the life of me I just can NOT figure it out! Any help would be much appreciated, thank you.
Here's the part where I try to do this:
$resultAddID = mysql_query("SELECT ADDRESS_ID FROM hospital");
while($resultAddID1=mysql_fetch_array($resultAddID)){
$resultAddID2[]=$resultAddID1['ADDRESS_ID'];
for ($i = 0; $i <= 2; $i++) {
$resultAddT = mysql_query("SELECT * FROM address WHERE ID = $resultAddID2[]");
$resultAddTm= mysql_fetch_array($resultAddT);
$resultAddT2[]=$resultAddTm['GOVER_ID'];
}
}
$response["hospADD"]= $resultAddT2;
You should add {}'s like
$resultAddT = mysql_query("SELECT * FROM address WHERE ID = {$resultAddID2[$i]}");
It would be better if you did something like this because you are querying the second item too many times
$resultAddID = mysql_query("SELECT ADDRESS_ID FROM hospital");
while($resultAddID1=mysql_fetch_array($resultAddID)){
$resultAddID2[]=$resultAddID1['ADDRESS_ID'];
}
for ($i = 0; $i <= 2; $i++) {
$resultAddT = mysql_query("SELECT * FROM address WHERE ID = {$resultAddID2[$i]}");
$resultAddTm= mysql_fetch_array($resultAddT);
$resultAddT2[] = $resultAddTm['GOVER_ID'];
}
$response["hospADD"]= $resultAddT2;
OR simpler yet:
$resultAddID = mysql_query("SELECT ADDRESS_ID FROM hospital");
while($resultAddID1=mysql_fetch_array($resultAddID)){
$resultAddT = mysql_query("SELECT * FROM address WHERE ID = {$resultAddID1['ADDRESS_ID']}");
$resultAddTm= mysql_fetch_array($resultAddT);
$resultAddT2[] = $resultAddTm['GOVER_ID'];
}
$response["hospADD"]= $resultAddT;

Displaying tagged images across multiple pages fails

I feel this is a more logic problem than anything. A database has pictures saved via a source reference and booleans for tags e.g. isLandscape=1. I had made a system to traverse pages of results based on types asked. The following is an example of what I'm facing. I only see the same 12 pictures from page 0 -> page 22. Then I start to see new ones. I think I have just been overlooking this bug since I had not noticed it until now. One thing I noticed was page22*12pictures = 264 which is the same as the first new picture id that is seen. You can see the error here (just change the p to different pages).
<?php
$pictureid = -1;
$startpage = 0;
$viewsection = -1;
$uid = -1; //user id
$amntperrow = 4; //how many pictures per row, must correlate with doThumb()'s switch case amounts
$maxrows = 3; //how many rows of pictures to drop
if(isset($_GET['pid']) && is_int(intval($_GET['pid']))) $pictureid = clean($_GET['pid']);
if(isset($_GET['sec']) && is_int(intval($_GET['sec']))) $viewsection = clean($_GET['sec']);
if(isset($_GET['p']) && is_int(intval($_GET['p']))) $startpage = clean($_GET['p']);
$result = generateResult(array("isFlowers"), $startpage);
//**snip** -- drawing thumbnails would happen here
function generateResult($types, $page) {
global $amntperrow;
global $maxrows;
$sqlWheres = "";
$idAmnt = ($amntperrow*$maxrows)*$page;
if(isset($types) && !empty($types)) {
if(count($types) >= 1) {
for($i = 0; $i<count($types); $i++) {
$sqlWheres .= $types[$i] . "='1'";
if($i < count($types)-1) $sqlWheres .= " AND ";
}
}
}
$result = "SELECT * FROM pictures WHERE ";
if(!empty($sqlWheres)) $result .= $sqlWheres . " AND " ;
$result .= " private='0' AND id >='" . $idAmnt . "' LIMIT " . ($amntperrow*$maxrows);
return $result;
}
?>
This seems like a glaring bug that I am overlooking. Thanks for the help.
What is the difference between these two queries?
SELECT *
FROM pictures
WHERE private = '0' AND id >= '24'
LIMIT 12;
and
SELECT *
FROM pictures
WHERE private = '0' AND id >= '36'
LIMIT 12;
Answer: potentially no difference at all. The database engine can decide in either case that it wants to return pictures with ids 100 through 111 - that result set meets all of the conditions of either query.
Try a query like this instead:
"SELECT *
FROM pictures
WHERE private = '0'
ORDER BY id
LIMIT " . $idAmnt . ", " . ($amntperrow * $maxrows)
The ORDER BY id is really the key. Paging through database results is generally done with a combination of ORDER BY and LIMIT.

Reading a field from the code, working with the data, saving the values to new fileds in the row

So here is what I am doing.
Read a row each in for loop. (Because all at once is going to take some resources since I am in a shared hosting.)
2.Get the right field data to a variable.
3.Manipulate the req datas dependant on the extracted field.
4.update the new fields where filed=extracted data.
Bit of addition, I am adding the current position to a file, so that the script can continue from there next time it is run.
Problem : It doesnt seem to work. The counter.txt gets values like 3-4, but it simply resides there. my db has like 1000k rows.
my code :
require ("dbconnect.php");
header("refresh:29;url=process.php"); // so it doesnt ever end. I cant use max_execution_time here for some reason.
$count = mysql_query("SELECT COUNT(*) FROM collection ");
$data = mysql_fetch_array($count);
$count = $data[0];
echo $count;
$countfile = fopen("counter.txt", "r");
$counter = fgets($countfile);
echo fgets($countfile);
while (fgets($countfile) <= $count)
{
$i = fgets($countfile);
$takeword = mysql_query("SELECT word FROM collection WHERE id='$i'") or die();
$wd = mysql_fetch_array($takeword);
$data = $wd[0];
$d1 = hash($algorith='md2',$data);
$d2 = hash($algorith='md4',$data);
$write = mysql_query("UPDATE collection SET md2='$d1', md4='$d2' WHERE id='$i'") or die(mysql_error());
//opens, empties and write the new pointer to the file. closes, and open the file in readmode for the next read at the loop.
$counts = fopen("counter.txt", "w+");
fwrite($counts, $counter + 1);
fclose($counts);
$countfile = fopen("counter.txt", "r");
}
Any help would be appreciated :) Looking for code optimization and killing the error. Suggestions would do.:)
Alright I'd do something like this (sorry about the delayed response, I kept forgetting)
<?php
//main execution
$sql = mysql_connect(...);
if (!$sql)
die ("No database connection");
if (!mysql_select_db(..., $sql))
die ("Database does not exist in this schema");
//Run the query for this iteration.
processQuery();
//---
function getQueryOffset($file)
{
$offset = 0; //default offset
if (file_exists($file)) //check if the counter file exists
{
$contents = file_get_contents($file); //get the contents of the counter
if ($contents !== FALSE && is_numeric($contents)) //check if an appropriate counter value
$offset = intval($contents);
}
return $offset;
}
function processQuery()
{
$table = "collection"; //table to update
$counter = "counter.txt"; //where to look for the last execution's offset.
$maxrows = 10000; //update 10,000 rows each time this file is loaded.
$sql = $GLOBALS['sql'];
//calculate the number of rows in the table
$qCount = mysql_query("SELECT COUNT(*) max FROM $table", $sql);
$aCount = mysql_fetch_assoc($qCount);
mysql_free_result($qCount);
$max = $aCount["max"];
$offset = getQueryOffset($counter); //calculate the offset (or a default 0)
if ($offset < $max) //if offet >= max, we're done.
{
$qUpdate = mysql_query("SELECT word, id FROM $table LIMIT $offset, $maxrows", $sql); //get the next "maxrows" rows from the table.
if ($qUpdate)
{
$assoc = NULL;
while (($assoc = mysql_fetch_assoc($qUpdate)) != NULL)
{
$md4 = hash("md4", $assoc["word"]); //calculate the hashes
$md2 = hash("md2", $assoc["word"]);
$id = $assoc["id"]; //id the row
mysql_query("UPDATE $table SET md2='$md2', md4='$md4' WHERE id=$id", $sql); //update the table columns
}
//update the offset in the counter file.
file_put_contents($counter, ($offset + mysql_num_rows($qUpdate)));
mysql_free_result($qUpdate);
}
}
}
mysql_close($sql);
?>
1 issue that I am seeing here:
Check your update query - that seems to be wrong. According to me, it should be "SET md2='$d1' AND md4='$d2'"
Another issue that I am not sure about:
I am unsure if md2 and md4 are valid names of hashing algorithms
A better way of doing this:
1. Dont write to file!
2. Create an additional column in your SQL by the name 'status', default value to 0. On update, change that value to 1.
3. Search for rows to edit based on query "SELECT word FROM collection WHERE status=0 limit 0,1"
4. OR if the columns md2 and md4 are empty in the original table, query could also be "SELECT word FROM collection WHERE md2='' and md4='' limit 0,1"
Hope this helps.

Generate a Unique ID using PHP and MYSQL

Hi I am creating a system that processes and ID and a UID, The UID we are generating randomly but I am a little stuck, I need to always generate a UID that does not currently exist in the db as the field is a unique field used on the front end so as not to expose the real ID.
So to recap, I am trying to generate a unique id that does not currently exist in the DB the part I haven't got working is the cross checking in the db so it sometimes will give a number that already exists in the db even though it shouldn't thanks in advance.
This is my code so far:
function uniqueID($table)
{
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$possible = '1234567890';
$code = '';
$characters = mt_rand(7,14);
$i = 0;
while($i < $characters)
{
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
$result = $db->query('
SELECT uniqueID
FROM '.$table.'
WHERE uniqueID = "'.$code.'"
LIMIT 1
');
$totalRows = $result->num_rows;
if(!$result)
{
return $db->error;
}
else
{
if($totalRows > 0)
{
return uniqueID($table);
}
else
{
return $code;
}
}
}
http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid
To generate unic UID you can use time, i think it was a very small chanse that records will be added in the same second, with two random data.
write some function which return it to you like that
function generate_uid(){
return md5(mktime()."-".rand()."-".rand());
}
In PHP there's a function called uniqid()
http://php.net/manual/en/function.uniqid.php
I could talk about generating ids, like the others did, but this is not your question.
Your query seems fine. If it returns 0 rows but you seem to find the code in the database, then most likely it only looks the same, but actually isn't. It could be padded by whitespace.
One way to solve this is by selecting the last row of your user database and have your script to check for the id field (you can achieve this by performing a select ordering by ID in descendent mode) then you can use that info for randomize numbers greater than that ID.
EDIT
$result = $db->query('
SELECT uniqueID
FROM '.$table.'
');
$already_in_database = array();
while ($row = mysql_fetch_array($result)){
$already_in_database[] = $row['UID'];
}
$new = rand(0,$some_max_value);
while(in_array($new,$already_in_database)){
$new = rand(0,$some_max_value);
}
I figured out what the problem was already, As I mentioned to everyone the code generation was not the issue! The issue was that the cross check was not working correctly. So all I did was removed this loop
while($i < $characters)
{
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
As this was causing my unique ID to end up wrong.

Categories