using pagination to output array - php

this is my code
//select all the members id
$result = mysql_query("select id from member");
//create array of ids
$id = array();
// page is the number of my pagination numbering and its from 1 to 10
$dis = $page;// for example $page = 1
// $page get its value every time a user click my pagination numbering i.e $page = $_GET[page];
// guess you understand
while($u_id = mysql_fetch_assoc($result)){
//id is my field name
$id[] = $u_id[id];
}
echo $id[$dis];
my problem is that this above code works for only 4 records out of 10records. my question is, why is it not working outputin other ids when the array index is 4,5... and howw do i amke it work
secondly the echo part is just the test of my idea but what i wanted to do is to pass the return id to a function for query. please any help

Well not sure if this is your problem but you might want to correct this if its not just a type in your post:
while($u_id = mysql_fetch_assoc($result)){
$id[] = $u_id['id']; // this should be 'id' not $id
}

I think you want to have:
while($u_id = mysql_fetch_assoc($result)){
$id[] = $u_id['id']; // changed from $id inside brackets
}

For starters, as you're using mysql_fetch_assoc(), your $u_uid variable will not contain any numeric indices. In fact, it will only ever have an 'id' key so your while loop should really look like this
$id[] = $u_uid['id'];
This will build the $id array with every id in your member table which is probably not what you want. As you mention pagination, I expect you actually want something like this
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$page = max(1, $page); // ensure page is 1 or greater
$rowCount = 5; // you can set this to whatever you want
$offset = ($page - 1) * $rowCount;
$result = mysql_query(sprintf('SELECT id FROM member ORDER BY id LIMIT %d, %d',
$offset, $rowCount));

Related

How to check array for existing elements to assign ticket numbers?

I am attempting to create a function which will tell me what free numbers are available to use, I have a function which returns the numbers which have already been taken in an array.
I wish to check the returned array with existing elements against a blank array, and if the number is not in the array then push/add it to the empty array to allow me to return an array of available numbers/tickets.
I have tried some examples on here and looked upon PHP documentation on some items trying array_intersect, in_array etc.
I believe the best way to add the free numbers to the empty array is using array_push which has not been implemented into the example code as of yet.
Available numbers function so far:
function freeNumbers($drawID){
$minTickets = 1;
$maxTickets = totalTickets($drawID);
$takenNumbers = takenNumbers($drawID);
$freeNumbers = array();
for($i = 1; $i<$maxTickets; $i++){
$x = $i-1;
foreach($takenNumbers as $v){
if(in_array($v, $freeNumbers)){
echo "Element is in array";
break;
} else {
echo $v . "is taken";
}
}
}
//return $freeNumbers;
}
Taken numbers function
function takenNumbers($drawID){
$connect = new mysqli("localhost", "root", "", "dream");
$stmt = $connect->prepare("SELECT * FROM transaction WHERE DrawID = ?");
$stmt->bind_param("i", $drawID);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows == 0) exit("No rows");
$tickets = array();
while($row = $result->fetch_assoc()){
$id = $row['ID'];
$tickets[] = $row['TicketNumber'];
}
return $tickets;
}
Max tickets is just counting from a database transaction table to count already assigned numbers.
In this current iteration of the project, I am receiving the following "1 is taken" for each loop.
Thanks in advance, I have attempted to explain what I am attempting to do in best terms possible. But if I haven't been able to describe something please reply so I can explain it further.
Instead of checking on each array item, you could get the the difference values between all of the ticket numbers and the taken ticket numbers array using array_diff() :
function freeNumbers($drawID){
$minTickets = 1;
$maxTickets = totalTickets($drawID);
$takenNumbers = takenNumbers($drawID);
$freeNumbers = array();
$allTickets = range(1, $maxTickets);
$freeNumbers = array_values(array_diff($allTickets, $takenNumbers));
//return $freeNumbers;
}
Edit : added array_values() to reset the array index returned from the array_diff() function.
Edit : Or if you prefer to use the array_push() function, you could do it like :
for($i = 1; $i<$maxTickets; $i++){
if(!in_array($i, $takenNumbers)){
array_push($freeNumbers, $i);
}
}

How to fill session array with data from database?

I know this question might be very basic for someone experienced. But I'm still in the learning process so I need some help.
I want to populate a session array with data that's coming from the database. There can be multiple items in the session array. I'm trying to do it like this -
$sql = mysqli_query($con, "SELECT * FROM `purchase_info_details` WHERE `purchase_details_id` = '$pur_det_id'");
while ($row = mysqli_fetch_array($sql)) {
$data[$i]['purchase_details_id'] = $row['purchase_details_id'];
$data[$i]['cid'] = $row['id'];
$data[$i]['item_id'] = $row['item_id'];
$data[$i]['unit_id'] = $row['unit_id'];
$data[$i]['quantity'] = $row['quantity'];
$data[$i]['price'] = $row['price'];
$data[$i]['conv_rate'] = $row['conv_rate'];
$_SESSION['list1_data']['purchase_details_id'] = $data[$i];
}
FYI: purchase_details_id is the primary key. This code works partially. What I mean is I only get one row from the table in my session array but I need to get all the rows from the table that matches my SQL query.
I've been searching for a relevant example on the internet but yet to find any. I'm really stuck with it and couldn't find any solution. Please help!
Thanks!!
The problem is that your are always overwriting the same data in your session array. When your loop is finished, you will have the last row from your dataset in your session array.
To add a new row in your session array everytime you can proceed with either:
$_SESSION['list1_data'][] = $data[$i];
or if you want a specific key from your data (assuming it is unique):
$_SESSION['list1_data'][$row['purchase_details_id']] = $data[$i];
try something like this
while ($row = mysqli_fetch_array($sql)) {
$data[$i]['purchase_details_id'] = $row['purchase_details_id'];
$data[$i]['cid'] = $row['id'];
$data[$i]['item_id'] = $row['item_id'];
$data[$i]['unit_id'] = $row['unit_id'];
$data[$i]['quantity'] = $row['quantity'];
$data[$i]['price'] = $row['price'];
$data[$i]['conv_rate'] = $row['conv_rate'];
$_SESSION["db_data"][$i] = $data[$i];// or just $_SESSION[$i] = $data[$i]
}
$_SESSION['list1_data']['purchase_details_id'] = $data[$i]; always overwrite and you get only last value . use $_SESSION['list1_data'][$row['purchase_details_id']] = $data[$i];
just assign array to session when you finish your loop . like below
$_SESSION['list1_data'] = $data;
or as you say product_id is unique then why you use $i ? (use $data[$row['purchase_details_id']]['purchase_details_id'] = value , use $data[$row['purchase_details_id']]['cid'] = value etc ...)
Do this:
$_SESSION['list1_data'][$row['purchase_details_id']] = $data[$i];
This way you can directly access specific details id from the session. For example:
$row = $_SESSION['list1_data'][1]; //row for the id = 1
Pro tip: Always check if the key is set or else you will get warnings =)
make sure that you are initialize the session() method, and you can make a 2 or 3 dimensional array as you need to keep the database value as #B-and-P mention in his comments.
thanks

How to echo columns 1...n from mysql database except the first one in php?

I have a table with par_id and columns (par1-5) 1 up to 5, but I'm trying to have my php function below to echo any number of columns
//-------------------------------------- get about ----------------------------------------------
function getAbout($option){
$div = array();
$sql_st = "undefined";
if($option == "about")
$sql_st = "SELECT * FROM `about` where par_id='1'";
// connect to database
mysql_connect($_SESSION['dbSever'],$_SESSION['dbUser'],$_SESSION['dbPass']) or die(mysql_error());
mysql_select_db($_SESSION['tblName']) or die(mysql_error());
$result = mysql_query($sql_st) or die(mysql_error()."<br/>".$sql_st);
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result) ){
// not sure what to do here
}
// disconnect
mysql_close();
return $div;
}
From your question title I'm assuming you have an ID maybe in your first column and you want to keep that from being printed. You could try something like:
$numberOfColumns = mysql_num_fields($result);
while ($row = mysql_fetch_array($result) ){
for ($i = 1; $i < $numberOfColumns; $i++){
echo $row[$i];
}
}
The $i iterator in the for loop is initiated with value of 1 because PHP handles (like many languages) arrays as zero-based, which means that the first element is referenced by $row[0] (as in this example) - by starting the loop at one and going for as many elements there are in the array, you're effectively grabbing all elements except for the first one.
A really simple one would be to have a flag like so:
$skippedFirstRow = false;
while ($row = mysql_fetch_array($result)){
if(!$skippedFirstRow) {
//do whatever you want here
}
$skippedFirstRow = true;
}
However, keep in mind that this is just a quick hack for what you want and considering your code, but it is not an elegant solution.

PHP getting data from mysql database for the Query string variable

Here is what I would like to do; I am passing an encoded data as a query variable to my webpage, then in my php page, I am decoding the data and checking the same in my database. The code I am using is shown below:
<?php
// Get the ID from URL.
$id = ( isset($_GET["id"]) && !empty($_GET["id"]) ? $_GET["id"] : "");
// If "id" is not empty, proceed.
if(!empty($id)) {
$id = base64_decode($id);
global $wpdb;
$res = $wpdb->query("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found.";
for( $i=0; $i<count($res); $i++) {
echo $res[$i]->id;
}
exit;
}
else {
echo "No ID";
exit;
}
?>
I have one record in my database. The above code correctly says "1 records found". I am not sure how to get the value of the field in that row. I have 3 columns, they are id, field1 and field2. The code "echo $res[$i]->id" returns nothing.
Please help
BTW, I am trying this in my Wordpress blog.
Thank you all for your suggestions. I tried your suggestions and here are my results:
$res = $wpdb->query("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";
it says 1 records found.
$res = $wpdb->get_row("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";
it says 0 records found.
$res = $wpdb->get_results("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = count($res);
echo $tot . " records found."."</br>";
it says 0 records found.
while ($row = mysql_fetch_array($res)) {
echo $row[0];
}
If I use mysql_fetch_array,
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/myfolder/mytheme/index.php on line 38.
line 38 is while ($row = mysql_fetch_array($res)) {.
What I am trying to accomplish:
I have a wordpress blog. All the above code goes into my index.php. I will pass a product id to my index.php via query string variable. I have created a new table called S_redirect in my wordpress database. I will retrieve the value of query string variable id and check the same in my database table. If record exists, then retrieve one of the column value (url of the product) from that table row and redirect to that product url. If the record doesn't exists then redirect to home page. hope this helps everyone to understand what I am doing.
Judging by $wpdb, it looks like this is a WordPress. Hopefully this will help:
http://codex.wordpress.org/Function_Reference/wpdb_Class
Update
Don't use count() to get the number of rows; use $wpdb->num_rows (no () because it's a property, not a function). The count() function always returns 1 for any non-null value that it doesn't recognize as a "countable" value (i.e., arrays and certain objects), so it's likely your code will always yield 1.
$tot = $wpdb->num_rows;
=====
If you run your query with get_results() instead of query(), then you can loop through the results like this:
foreach ($res as $row) {
echo $row->id;
}
Ultimately, I think your code will end up looking like this:
$res = $wpdb->get_results("SELECT * FROM S_redirect WHERE source = ".$id);
$tot = $wpdb->num_rows;
echo $tot . " records found.";
foreach ($res as $row) {
echo $row->id;
}
Disclaimer: This is untested, as I've never used WordPress. This is just how I understand it from the documentation linked above. Hopefully it at least gets you on the right track.
Use:
$tot = count(mysql_fetch_array($res));
or
$tot = mysql_num_rows($res);
The best is
while($row = mysql_fetch_assoc($res)){
echo $row['column_name'];
}

php array selection

I have the following code and want to manually select an array:
<?php
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' ");
while($article= mysql_fetch_array($articleQuery )){
$aid = $article['id'];
$media = $article['media'];
$link = $article['link'];
}
echo $aid[0];
?>
The problem is that its not really selecting/displaying the correct information. What I want is to be able to select the value of the first array.
Thanks in advance.
$firstrow = null;
while($article= mysql_fetch_array($articleQuery)) {
if ($firstrow === null)
$firstrow = $article;
$aid = $article['id'];
$media = $article['media'];
$link = $article['link'];
//manipulate $aid, $media and $link.
}
//manipulate $firstrow
If you only need the first row, limit the query to one result and execute mysql_fetch_array at most once, instead of in a loop.
Or you can do like this:
$array = array();
while($article = mysql_fetch_object($articleQuery )){
$array[] = $article;
}
echo $array[0]->id; // get first id
echo $array[0]->media; // get first media
echo $array[0]->link; // get first link
echo $array[1]->id; // get second id
echo $array[1]->media; // get second media
echo $array[1]->link; // get second link
// and so on.......
if you want $aid to be an array, you should do something like that:
$aid = array();
while($article= mysql_fetch_array($articleQuery )){
$aid[] = $article['id'];
}
The problem is that its not really
selecting/displaying the correct
information. What I want is to be able
to select the value of the first
array.
What you want is propably this:
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' ");
$article= mysql_fetch_array($articleQuery);
echo $article[0];
You have unnecessary loop. You can also add "limit 1" to sql query. Although I'm not sure I understand your goal correctly.
Using mysql_fetch_assoc, will use the field names as the array indexer, so $article['id'] instead of $article[0]. That way if you change the definition of the table by adding new columns, your code won't break!
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' LIMIT 1");
$article= mysql_fetch_assoc($articleQuery);
var_dump($article);
If you really only want the first result:
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' LIMIT 1"); // note LIMIT clause
if( false !== ($article = mysql_fetch_array($articleQuery )))
{
$aid = $article['id'];
$media = $article['media'];
$link = $article['link'];
}
echo $aid;
If you want them all, but indexable:
$articleQuery = mysql_query("SELECT * FROM articles WHERE topic = 'IT' ");
while($article= mysql_fetch_array($articleQuery ))
{
$aid[] = $article['id'];
$media[] = $article['media'];
$link[] = $article['link'];
}
echo $aid[0];
Why not edit your SQL statement to select only one item?
mysql_query("SELECT * FROM articles WHERE topic = 'IT' LIMIT 1");
But the error in your code, is that you're looping over all your selected records, overwriting your variables on each pass. If you want to store all the rows as an array, you should modify your syntax like this:
while($article= mysql_fetch_array($articleQuery )){
$aid[] = $article['id'];
$media[] = $article['media'];
$link[] = $article['link'];
}
...after which you could access the first row with aid[0].
But instead I'd suggest a different structure:
while($article= mysql_fetch_array($articleQuery )){
$articles[]['aid'] = $article['id'];
$articles[]['media'] = $article['media'];
$articles[]['link'] = $article['link'];
}
What that does, is collect all the data into a single data structure, where each record holds all the data related to the article. You would access it like this:
echo $articles[0]['aid'];
echo $articles[0]['media'];
echo $articles[0]['link'];
If this looks like hebrew to you, take a look at the PHP manual section for arrays.

Categories