PHP next MySQL row - how to move pointer until function checks true? - php

I have a PHP script which takes a value from a row in my MySQL database, runs it through a function, and if it determines it's true returns one value, and if it's false, it needs to go to the next value in the database and check that one until eventually one returns true.
I think I need to use mysql_fetch_assoc, but I'm not really sure in what way to use it... I wish I could post my code to be more specific, but it's a lot of code and most of it has no bearing on this issue...

Is the "function" something you could do in the database instead? It's really inefficient to process every row in the table to check for some type of condition. That's exactly what databases are good at, namely, processing queries efficiently and getting answers to you quickly.
So I'd recommend looking at how to do it all on the database side so that your PHP code is just fetching the end result (i.e. rows filtered by the function). Maybe if you provide more details of what your "function" is doing, a more specific answer can be provided.

You can use mysql_fetch_array, and just jump on the values fetched using $row[id] and not $row['name'].
Say your function returns true, you'd just use $row[lastid+1].
If the ID isn`t incremental, this could work :
$qry_result = mysql_query($qry) or die(mysql_error());
while ($row = mysql_fetch_array($qry_result)) {
$result = yourfunction($row['whatever');
if ($result != false)
break;
}
Also there is a php function next() which advances a pointer to the next array element. In your function you could implement an array builder, and then cycle between the elements with this. Depends on what your function actually does or script purpose is. It could lead to some load if there are alot of results.

You should not check database this way, as mentioned above. Database has a little difference from the plain text file.
You should not have a field in your database that has a bunch of values separated by value1:value2|value1:value2|value1:value2. It must be separate fields. Database has a little difference from the plain text file and you better learn it.

You could try something like this:
SELECT *
FROM table
WHERE field NOT LIKE '%$sessionvar:%';
I think that is what you are after?

Related

Multiple MySQL updates from a string using PHP

I need some help putting together this PHP SQL update. I am pretty sure I need a foreach loop to post this query, but I am not sure how to write it.
Basically it needs to match ticketID from the string to ticketID in the database and update that row with the following developer.
The query string will look something like:
ticketID=1483&developer=Reme&ticketID=1484&developer=Reme&ticketID=1485&developer=Reme&isActive=1
Although there could be as many as 30/40 pairs with isActive being a variable to end it all. DBConn and all that is already set up, this is the last thing I need to solve before moving onto sessions.
This is being posted over using an Ajax call. Everything I need is arriving at its destination; it's just getting each pair and update in the database accordingly that I am stumped on.
You can't use the same parameter (ticketID) twice in a query string, because the second will overwrite the first.
In this case you have to use an array:
ticketID[]=1483&developer[]=Reme&ticketID[]=1484&developer[]=Reme&ticketID[]=1485&developer[]=Reme&isActive=1
And then you could use a foreach to loop.
It depends on how you want to update them, but I would suggest using JSON or some other more defined structure.
If you do
ticketID[]=1483&developer[]=Reme&ticketID[]=1484&developer[]=Reme&ticketID[]=1485&developer[]=Reme&isActive=1
you will have one array for ticketID, one array for developer, etc. Which means that you should be really careful with the other on which you are placing the parameters.
Instead of that I would prefer structure like this:
["isActive":1,
"tickets":{"ticketID" :1483
"developer": "Reme"},
{"ticketID": 1484
"developer": "Reme"},
{"ticketID": 1485,
"developer": "Reme"}]
On that you are confident that you are updating the right properties on the right object.

Is it possible to select all id's without a while-loop

I'm not sure if there is an answer for this, but I was thinking about the fact that PHP isn't very fast with while loops. That got me thinking about a basic function, which does something like this:
$array = array();
$sItem = DB::cms_query("SELECT id FROM someTable");
while($fItem = $sItem->fetch_assoc() ){
$array[] = $fItem['id']; // store the id in an array
}
That will give me an array with all found id's. What I was wondering is this:
Is it possible to select all those id's in 1 query and only use one fetch (so no loops to fetch), without creating difficult code. The goal is a simple piece of code to select all id's.
Small edit: I could replace fetch_assoc() with fetch_row() to improve a tiny bit, but I'm looking to replace the loop
To answer some questions:
I'm using mysqli, in my own custom database class (I'm new to OO, so in time I might improve that, but thats another story)
No, the mysqli extension doesn't provide any way to fetch all rows with a single operation, you can only fetch them one at a time. The only PHP API that currently offers this feature is PDO.
but I was thinking about the fact that php isnt very fast with while loops
How much ids are you fetching and what is called "not fast" for you?
I think the reason for a bad performance would most likely not be a while loop, but some other glitch with your code...

Is there a way using php to take a mysql query result

Is there a way using php to take a MYSQL query result, get a value from a column in the first record fetched, and then put that record back into the query result so when when looping over the result set later, that record can be used again? If this is possible, can I put the record back in the first position again?
Or should I return the value that I need from that first row as a separate variable in my routine in MYSQL. If this would be the better route to take, can someone give me some insight on how to return both a query result set and a separate variable as well? I cannot seem to get this to work either.
Or would the best way to do this be to create my own array from the query result set and then manipulate the mysql result set as need? I'm trying to stay away from this just to cut out the step of creating that array if one of the above two options is possible, otherwise I will just go with this.
Thanks in advance.
Just before you need to loop through again, you could use mysql_data_seek($query, 0);
Then the next call to fetch will be the first row again.
I haven't personally used it, but that's what I understood from the php manual:
http://us.php.net/manual/en/function.mysql-data-seek.php
I agree with the answers above but just to state it a slightly different way:
There is no point rewinding a pointer inside the query result object. You have to keep track of where it is, and it's easy to mess up, and it isn't worth the tiny speed increase.
It's much better to make a copy of the entire array and access the records using keys. Much easier to keep track of what is going on.

Take SQL input in PHP and output query results to the page

Basically I'm looking to create a page using PHP that will take SQL input, and output the results returned by the DB (MySQL). This is not for a production website (I understand the security implications). It's more for learning and practice. Kind of like the SQL console section of phpMyAdmin, or even similar to what sqlzoo.net can do (I think they are using perl, but I'd like to do it in PHP). Is there a practical way to accomplish this?
For example, how can I create a page in PHP/HTML to display a table of results when I don't know how many columns the query will return?
Also, what is the most practical way to allow a visitor to this web page to restore the DB to a default state with the original data? (e.g. create a sql dump of the original state and make a button that runs it? or is there a better way?)
Thanks!
Use * in your SQL query to fetch all columns and loop over the results from mysql_fetch_row() or mysql_fetch_assoc() with foreach.
Besides that, have you thought of using the mysql CLI ? It's useful for those requirements.
This question should be more specific than it is now.
"create a sql dump of the original state and make a button that runs it?" - Yes. But make sure you drop/delete the existing data.
You may have to run at least two queries... first return one row using LIMIT 1, and count the returning elements (using PHP count($row) if you use mysql $row = fetch_row($handle) ) to count the columns, and you can use SQL COUNT() to find out how many rows would be returned.
As for returning data to original state, I think a drop/recreation from a dump like you said may be the simplest and most reliable option.
Your best option is just running the query, checking if the amount of rows > 0, and then if it is, loop through the query resultset in a foreach and just show whatever you like.

call database row in to a function

I am writing a function which is called into a page, but I am not sure how to call information form database into the function in order to use them. Basically I am doing some calculation in the function where I need information form database to do them.
Is there anyone who can give a clue on how ot do this? Many thanks F
From a comment...
What I am trying to do is this: I have
a page in php which retieves some info
from database and all works fine. I am
writing a function that needs to make
some calculation based on some fields
in the database. What I cannot solve
is how to get this information form
the database into my function. I have
tired this: function CalculateCost ()
{ $low_season =
$row_rsbooking['cost']; etc. etc. then
making some calculations but I am
getting nowhere. I am not sure if the
function is getting the information
form database in order to make
calculation.
This is an older question, but as it remains unanswered, I will proffer my two cents.
From your comment to Rafael, it looks like your problem is variable scope. I think you want something like this
function add_one($cost)
{
// just something irrelevant to do
return $cost + 1;
}
// query stuff here, leaving $row with the results
$new_value = add_one($row_rsbooking['cost']);
In other words, pass the column value you need to the function and process the results it returns. If you need to alter your actual row, you could pass the whole row by reference (i.e. add_one(&$row)) and modify it in your function.
Without some more code from you, this is my best guess.
I am not sure I understand the question. But will try to answer it the best way I can.
If you are looking for help on how to connect to a database and execute a query, then have a look at the following link:
http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx
It describes how you can use the SQL Command object to get data from a SQL Server database in the form of a Dataset. Once this is done, you can get a dataset or datatable to get data to any function in your code for calculations.
You could also use an odbccommand. I would post a link, but I don't have enough reputation points to do more than one! :o)
If the Dataset is too big, you could consider using a datable or a SQLDataReader. Again, please have a look at the MSDN for info on those classes.
I hope this helps!
Rafael Jovel
www.augensoftwaregroup.com

Categories