Can anyone explain what the following PHP Code does
function query($query_string)
{
if ($query_string == "") {
return 0;
}
if (!$this->connect()) {
return 0;
};
if ($this->QueryID) {
$this->free_result();
}
if ($this->RecordsPerPage && $this->PageNumber) {
$query_string .= " LIMIT " . (($this->PageNumber - 1) * $this->RecordsPerPage) . ", " . $this->RecordsPerPage;
$this->RecordsPerPage = 0;
$this->PageNumber = 0;
} else if ($this->RecordsPerPage) {
$query_string .= " LIMIT " . $this->Offset . ", " . $this->RecordsPerPage;
$this->Offset = 0;
$this->RecordsPerPage = 0;
}
$this->QueryID = #mysql_query($query_string, $this->LinkID);
$this->Row = 0;
$this->Errno = mysql_errno();
$this->Error = mysql_error();
if (!$this->QueryID) {
$this->halt("Invalid SQL: " . $query_string);
}
return $this->QueryID;
}
function next_record()
{
if (!$this->QueryID) {
$this->halt("next_record called with no query pending.");
return 0;
}
$this->Record = #mysql_fetch_array($this->QueryID);
$this->Row += 1;
$this->Errno = mysql_errno();
$this->Error = mysql_error();
$stat = is_array($this->Record);
if (!$stat && $this->AutoFree) {
$this->free_result();
}
return $stat;
}
Can the above be done in a simpler way , would it be wise to use an ORM ?
The first class method looks like it performs a MySQL query and adds a LIMIT clause for pagination. The second moves the current query onto the next record, while incrementing the pagination counters.
In more detail, here's the first sample:
Exit the method if the query is empty or the database connection doesn't exist.
Free any existing query.
If the number of records per page and page number are set:
Add them to the LIMIT clause of the query.
And reset them to 0.
Otherwise if records per page is set:
Add it to the LIMIT clause of the query.
And reset them to 0.
Run the query.
Set the current row to 0.
Collect errors.
If the query failed halt with the error.
Return the query.
And the second:
If the query is not set halt with an error.
Fetch row information as an array for the current row.
Increment the row number.
Catch any errors.
If the result isn't an array free/close the query.
Otherwise return the result set.
Yes you are right Ross it something like pagination function in a class which calls the records one by one.
Related
status stored has value 'LET, SALE, LET/SALE'
My php code does not return as expected, I wish if ($input['status'] = "SALE") will return 'SALE, LET/SALE' but it return only LET/SALE
I have tried to amend the code many ways, but can't work probably
if (!empty($input['status']))
{
{
if ($input['status'] = "SALE");
{
if (is_null($where))
{
$where = "WHERE";
}
else {
$where = "AND";
}
$query .= " $where status LIKE '%".$input['status']."%' AND `selling` <=
{$input['max_price']}";
}
}
{
if ($input['status'] = "LET");
{
if (is_null($where))
{
$where = "WHERE";
}
else {
$where = "AND";
}
$query .= " $where status LIKE '%".$input['status']."%' AND `rental` <=
{$input['max_price']}";
}
}
}
I wish to query property LET or SALE at condition max_price. Lets say if query SALE with max 100,000 return results shall include SALE, LET/SALE with max_price less than 100,000
You are assigning a value in your "if" statement. Use == (is equal to) instead of = (equals). What's happening is that it reassigns the value each time and stays at the last choice, which was LET/SALE
Change to:
if ($input['status'] == "SALE");
and do that for all of your "ifs"
How to make codeigniter function that works same as insert_batch() but generates query Like INSERT IGNORE INTO ?
I need INSERT IGNORE INTO because one of my table's key is unique and its showing error when duplicate entry comes.
I searched code for add "INSERT IGNORE INTO " instead of "INSERT INTO" in codeigniter batch insert query but I didn't found results for that.
Yes we can made our custom batch insert query by using PHP login But if you want to do it in codeigniter use this function.
Add this function in (codeigniter/system/database/DB_active.rec.php).
/*
*Function For Batch Insert using Ignore Into
*/
public function custom_insert_batch($table = '', $set = NULL)
{
if ( ! is_null($set))
{
$this->set_insert_batch($set);
}
if (count($this->ar_set) == 0)
{
if ($this->db_debug)
{
//No valid data array. Folds in cases where keys and values did not match up
return $this->display_error('db_must_use_set');
}
return FALSE;
}
if ($table == '')
{
if ( ! isset($this->ar_from[0]))
{
if ($this->db_debug)
{
return $this->display_error('db_must_set_table');
}
return FALSE;
}
$table = $this->ar_from[0];
}
// Batch this baby
for ($i = 0, $total = count($this->ar_set); $i < $total; $i = $i + 100)
{
$sql = $this->_insert_batch($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_keys, array_slice($this->ar_set, $i, 100));
$sql = str_replace('INSERT INTO','INSERT IGNORE INTO',$sql);
//echo $sql;
$this->query($sql);
}
$this->_reset_write();
return TRUE;
}
To use this function
$this->db->custom_insert_batch($table_name, $batch_data);
Thanks !
Before I begin, I want to point out that I can solve my problem. I've rehearsed enough in PHP to be able to get a workaround to what I'm trying to do. However I want to make it modular; without going too much into detail to further confuse my problem, I will simplify what I am trying to do so that way it does not detract from the purpose of what I'm doing. Keep that in mind.
I am developing a simple CMS to manage a user database and edit their information. It features pagination (which works), and a button to the left that you click to open up a form to edit their information and submit it to the database (which also works).
What does not work is displaying each row from MySQL in a table using a very basic script which I won't get into too much detail on how it works. But it basically does a database query with this:
SELECT * FROM users OFFSET (insert offset here) LIMIT (insert limit here)
Essentially, with pagination, it tells what number to offset, and the limit is how many users to display per page. These are set, defined, and tested to be accurate and they do work. However, I am not too familiar how to handle these results.
Here is an example query on page 2 for this CMS:
SELECT * FROM users OFFSET 10 LIMIT 10
This should return 10 rows, 10 users down in the database. And it does, when I try this command in command prompt, it gives me what I need:
But when I try to handle this data in PHP like this:
<?php
while ($row = $db->query($pagination->get_content(), "row")) {
print_r($row);
}
?>
$db->query method is:
public function query($sql, $type = "assoc") {
$this->last_query = $sql;
$result = mysql_query($sql, $this->connection);
$this->confirm_query($result);
if ($type == "row") {
return mysql_fetch_row($result);
} elseif ($type == "assoc" || true) {
return mysql_fetch_assoc($result);
} elseif ($type == "array") {
return mysql_fetch_array($result);
} elseif ($type == false) {
return $result;
}
}
$pagination->get_content method is:
public function get_content() {
global $db;
$query = $this->base_sql;
if (!isset($_GET["page"])) {
$query .= " LIMIT {$this->default_limit}";
return $query;
} elseif (isset($_GET["page"]) && $_GET["page"] == 1) {
$query .= " LIMIT {$this->default_limit}";
return $query;
} elseif (isset($_GET["page"])) {
$query .= " LIMIT {$this->default_limit}";
$query .= " OFFSET " . (($_GET["page"] * $this->default_limit) - 10);
return $query;
}
}
And my results from the while loop (which should print out each row of the database, no?) gives me the same row everytime, continuously until PHP hits the memory limit/timeout limit.
Forgive me if its something simple. I rarely ever handle database data in this manner. What I want it to do is show the 10 users I requested. Feel free to ask any questions.
AFTER SOME COMMENTS, I'VE DECIDED TO SWITCH TO MYSQLI FUNCTIONS AND IT WORKS
// performs a query, does a number of actions dependant on $type
public function query($sql, $type = false) {
$sql = $this->escape($sql);
if ($result = $this->db->query($sql)) {
if ($type == false) {
return $result;
} elseif ($type == true || "assoc") {
if ($result->num_rows >= 2) {
$array;
$i = 1;
while ($row = $result->fetch_assoc()) {
$array[$i] = $row;
$i++;
}
return $array;
} elseif ($result->num_rows == 1) {
return $result->fetch_assoc();
}
} elseif ($type == "array") {
if ($result->num_rows >= 2) {
$array;
$i = 1;
while ($row = $result->fetch_array()) {
$array[$i] = $row;
$i++;
}
return $array;
} elseif ($result->num_rows == 1) {
return $result->fetch_array();
}
}
} else {
die("There was an error running the query, throwing error: " . $this->db->error);
}
}
Basically, in short, I took my entire database, deleted it, and remade another one based on the OOD mysqli (using the class mysqli) and reformatted it into a class that extends mysqli. A better look at the full script can be found here:
http://pastebin.com/Bc00hESn
And yes, it does what I want it to. It queries multiple rows, and I can handle them however I wish using the very same methods I planned to do them in. Thank you for the help.
I think you should be using mysql_fetch_assoc():
<?php
while ($row = $db->query($pagination->get_content())) {
print_r($row);
}
?>
I have a php script for check the availability of some data. I call this script from external jquery. the jquery is running fine. here is my php:
<?php
$avares = checkAva($fi_nm, $tbl_nm, $txtval);
echo $avares;
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table . "") or die("query failed");
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
if ($curval == $dbval) {
return "no";
} else {
return "yes";
}
}
}
?>
$curval is the variable coming from external jquery. my problem is that the while loop seems to run only once though there are lot of entries in the DB. I checked it with an integer variable and the while loop seems to run only once. can you help me to solve that?
Look at your code.
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
if ($curval == $dbval) {
return "no";
} else {
return "yes";
}
}
you have used return, if its true it returns and false then also returns change those according to your needs. The return statement immediately ends execution of the current function
It will by design as you have a return statement. From what you have said your not actually wanting it to return but to set a variable that at end of execution will return no or yes. I could be wrong on this but hey ho.
<?php
echo checkAva($fi_nm, $tbl_nm, $txtval);
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table) or die("query failed");
$noOrYes = "yes";
while ($a_row = mysql_fetch_array($avres)) {
if($curval == $a_row[$field]) {
$noOrYes = "no";
}
}
return $noOrYes;
}
?>
The possible issue that can cause Loop to iterate once are:
Error in the Variable used for the $query and $result
Same name Variable inside and outside of the Loop
Incorrect placement of Return statement
Invalid Mysql Statement
Directly put the condition in your Query like
function checkAva($field, $table, $curval) {
$avres = mysql_query("SELECT " . $field . " FROM " . $table . "
WHERE `".$field."` = '".$curVal."'");
$res = mysql_fetch_array($avres);
if(is_array($res) && count($res) > 0)
return "Yes";
else
return "No";
}
Instead of getting all the results and checking with each one of the result you directly put a condition to extract the results which satisfies your condition.This will be suggestable if you have many records.
You need to put one of the return outside of the while loop.
For example if you just wanted to check if $curval == $dbval
while ($a_row = mysql_fetch_array($avres)) {
$dbval = $a_row[$field];
//If the condition was met return with a no
if ($curval == $dbval) {
return "no";
}
}
//If the condition was not met return yes
return yes;
That's basically what you need to do so the loop will run until your condition was met or not at all.
my problem is this
i am fetching a mysql row via this
$sql_istorrenthere = $this->query_silent("SELECT media_type
FROM " . DB_PREFIX . "auction_media WHERE
auction_id='" . $item_details['auction_id'] . "'");
$row = mysql_fetch_array($sql_istorrenthere);
and then calling it with this
if ($row['media_type'] == 4)
{
$display_output = GMSG_TORRENT;}
else
{
$display_output = GMSG_NOTORRENT;
}
}
however, media_type has multiple values, (1,2,3,4)
how to write it so that it checks if 4 exists? because now i believe it is checking if media_type equals 4 and that is false, which is giving me the wrong display_output
You can use mysql_num_rows to determine if any rows were returned, and this works by adding a search condition in your query adding " AND media_type = 4" to the end
if(mysql_num_rows($sql_istorrenthere)) {
} else {
}
// You can loop through records by doing the following, this prints out every media type :)
while ($row = mysql_fetch_array($sql_istorrenthere)) {
echo $row['media_type'] . '<br />';
}
You can just add on "AND media_type = '4'" to your query. But you really should use paramaterized queries.
Once your query has "AND media_type = '4'" you can check RowCount.
There are probably better ways, but here's one idea.
$media_type_ids = explode(',', $row['media_type']);
if (array_search(4, $media_type_ids) !== FALSE) {
// found
}
It could be possible to even do this in-situ in the database query ... potentially.
// Comment the next line after you get what it is
#print ("Value of media type is: >>>".$row['media_type']."<<<"); // Line to be commented
if (isset($row['media_type']) && $row['media_type'] == 4) {
$display_output = GMSG_TORRENT;
}
else {
$display_output = GMSG_NOTORRENT;
}
To fetch all media types:
<?php
$sql_istorrenthere = $this->query_silent("SELECT media_type FROM " . DB_PREFIX . "auction_media");
while ($row = mysql_fetch_array($sql_istorrenthere)) {
// Comment the next line after you get what it is
#print ("Value of media type is: >>>".$row['media_type']."<<<"); // Line to be commented
if (isset($row['media_type']) && $row['media_type'] == 4) {
$display_output = GMSG_TORRENT;
}
else {
$display_output = GMSG_NOTORRENT;
}
}