passing id via url to second page - php

I am trying to pass id to second page which I am selecting from another table but the below code isn't working. When I do var_dump I can see that the values are what I want but the rows for main query don't show up(The title and image aren't being displayed).
I have two queries in which the one is inside the other one. Can someone help me out? The main query works fine if I get rid of the while loop of the second query.
$paginate = new pagination($page, "SELECT * FROM table1 where title != '' ORDER BY id desc" , $options);
}
}
catch(paginationException $e)
{
echo $e;
exit();
}
if($paginate->success == true)
{
$result = $paginate->resultset->fetchAll();
foreach($result as $row)
{
$dx = $row['image_one'];//image_one from main query
//second query
$item = $mydb->prepare("select * from table2 where imageone = ?");
$item->bind_param('s', $dx);
$item->execute();
$item_res = $item->get_result();
while($row = $item_res->fetch_assoc()){
$rx = $row['id'];
var_dump($rx);
} //the rows below aren't being displayed
$path = 'images/';
echo "<a href='second.php?title=".urlencode($row['title'])." &item=".$row['id']."&id=".$rx."'>"."<img src='".$path."".$row['image_one']."'/></div>"."</a>";
}

Try this:
echo "<a href='second.php?title="'.urlencode($row['title']).'" &item="'.$row['id'].'"&id="'.$rx.'"'>"."<img src='"'.$path.'"".$row['image_one']."'/></div>"."</a>";
use ' ' around var name

You are reassigning $row in your while loop once it exits $row is null.
Try this instead:
while($item_row = $item_res->fetch_assoc()) {
$rx = $item_row['id'];
}
Also, instead of nested queries you should try using a join.

Related

Create PHP array out of table column

I am trying to create a loop that displays each row in a table. I think I need to make an array out of the PK, but I can't figure out how to do that. Here is my code so far:
$conn = dbConnect('read');
$getData = 'SELECT * FROM table';
$allData = $conn->query($getdata);
if (!$allData) {
$error = $conn->error;
} else {
$data = $allData->fetch_assoc();
$rowId = array($data['PK']);
} while ($rowId <= count($rowId)) {
// code to be run for each row
$rowId++;
}
EDIT: Sorry my question is confusing, I'm new to PHP.
Your question is a bit confusing but I think this is what you are trying to do:
$sql = 'SELECT * FROM table';
$query = $conn->query($sql);
while ($row = $query->fetch_assoc()) {
$data[$row['PK']] = $row;
}
That would iterate over each row, creating an array and using the row's value for column PK as an associative array key.
fetch_assoc() (I assume mysqli here now) doesn't fetch all data from a result, but one row after each other. So you don't need to make an array of $row['PK'], but need to loop over the results.
$conn = dbConnect('read');
$getData = 'SELECT * FROM `table`'; // you would need backticks here, if the table really is called "table" (what you shouldn't do...)
$result = $conn->query($getData); // it's not 'allData', it is a result_set. And be carefull about Case! $getData!=$getdata
if (!$result) {
$error = $conn->error;
} else {
$cnt=0;
while($row = $result->fetch_assoc()) {
// code to be run for each row
// you can display $row['PK'] now:
echo $row['PK'];
// or add that value to something else, whatever you need
$cnt = $cnt+$row['PK'];
// or to have a new array with the values of one table-column:
$columnRows[] = $row['PK'];
}
// now you can use the created array
foreach($columnRows as $PK) {
echo $PK;
}
}

Pick a row with a specific index in a foreach loop

I want to output all image files of a specific productid. What is the right syntax to output the image path for row 1, row 2, row 3 etc? I can not find it.
$sql = "SELECT *
FROM images
WHERE productid = $productid";
$select = $db->prepare($sql);
$select->execute(array());
foreach($select as $index => $rs) {
if($rs['imagepath']){
if($index == 0){
echo $imagepath[0]; // <---What is the right sytax of this?
}
}
if($rs['imagepath']){
if($index == 1){
echo $imagepath[1]; // <---and this?
}
}
if($rs['imagepath']){
if($index == 3){
echo $imagepath[2]; // <---and this?
}
}
The whole point of a foreach loop is it goes once through each select as "index". so you shouldn't have to worry about making an if-statement for each possible row, just make the statement once, and it will happen on each and every iteration
$rows = [];
$sql = "SELECT *
FROM images
WHERE productid = productid";
$select = $db->prepare($sql);
$select->execute(array());
foreach($select as $index => $rs) {
$rows []= $rs;
}
echo $rows[0]['imagepath'];
aren't we missing the fetch function?
`
$select = $db->prepare($sql);
$select->execute(array());
$i = 0;
while($row = $select->fetch()) {
echo $i . ' '. $row['imagepath'] . '<br>';
$i++;
}
?>
`
--
addendum:
I now understand you only want one, or some, of the images to be shown.
Would it not be easier then, to only select that/those images?
SELECT imagepath
FROM images
WHERE productid = productid
AND someid = 3
or if no "someid" is present:
SELECT imagepath
FROM images
WHERE productid = productid
LIMIT 2,1
That would avoid the need to loop through may be 100 records to only use the 3th.

Variable URL PHP and MySQL

Just trying to pass a variable on URL so that when echoed I can click on it and open it's own content based on the database record. Right now this one shows all the records from database but what I was trying to do was pass a URL so each blog IDs will have it's own URL and when clicked on it will open the individual entries rather than all the entries.
Edited Now I'm able to show rows of entries with IDs where 'IDs' has URL variable at the end. Do I need to create another query to echo the individual entry on my mini blog?
<?
$db = // connection to db and authentication to connecting to db;
#$postID = $_GET['postID']; // I'm thinking to use a $_GET global variable to work with URL variable
$command = "select * from $table_name"; // I'm thinking to add the Id here or something or create another query to echo the linked URL 'viewblog.php?postID=$data->blogID'
$result = $db->query($command);
while ($data = $result->fetch_object()) {
echo "<TR><TD><a href='viewblog.php?postID=$data->blogID'>".$data->blogID."</a></TD>";
echo "<TD>".$data->author."</TD>";
echo "<TD>".$data->date."</TD>";
echo "<TD>".$data->entry."</TD></TR>\n";
}
$result->free();
$db->close;
Why this script is giving all entries?
Because the final query that is being sent to the database is something like
select * from TABLE_NAME
which will return all entries since your are using the asterix * after SELECT
What you are asking for can be obtained if the executed final query contains the "blogID" before retrieving the results and start fetching them.
http://www.w3schools.com/sql/sql_where.asp
You should also use the fetched or post ID in the echoed result (so that when clicked, each blog has its own id in the link).
It could be something like this
$postID = $_GET['postID'];
//Add filtering by id to select statement
$command = "select * from '$table_name' obj WHERE obj.blogID = '$postID'";
$result = $db->query($command);
while($data = $result->fetch_assoc()){
$data['blogID'] = $postID;
//Add ID to echoed link
echo "<TR><TD> Some Blog (ID: ".$data['blogID'].") </TD>";
echo "<TD>".$data['author']."</TD>";
echo "<TD>".$data['date']."</TD>";
echo "<TD>".$data['entry']."</TD></TR>\n";
}
WATCH OUT for security issues regarding this code. You should use a safer way to do this. I'm only explaining the results.
As for Auto Increment, it can be initiated when you first created the table. This is for when you INSERT a new row into the database. When you use Auto Increment, you don't have to give an ID manually.
http://www.w3schools.com/sql/sql_autoincrement.asp
Notice : The HTML BR ELEMENT should not be used inside TABLE structures.
Hope it helps.
You could create some function like this for returning single post based on url
function single_blog($Post_id){
$sql = "SELECT * FROM your_table WHERE post_id = ? LIMIT 1";
$stmt = $this->db->prepare($sql);
$stmt->execute(array($Post_id);
return $stmt->fetch();
}
You are selecting all entries from your table. Use the following:
$db = // connection to db and authentication to connecting to db;
$postID = $_GET['postID']; // ??
$db->real_escape_string(trim($postID));
$command = "select * from $table_name WHERE `postID`=$postID";
$result = $db->query($command);
// Ensure results before outputting
if ($result->num_rows) while($data = $result->fetch_assoc()){
$data['blogID'] = $postID;
echo "<TR><TD><a href='viewblog.php?postID='>".$data['blogID']."</a> </TD>"; //??
echo "<TD>".$data['author']."</TD>";
echo "<TD>".$data['date']."<BR></TD>";
echo "<TD>".$data['entry']."</TD></TR>\n";
} else echo "No entry found!";
$result->free();
$db->close;
<?php
//$db connect to database
// Entry form sanitation of $_POST
// Insert PHP file to MySQL
// View all blog posts
$postID = $_GET['postID']; // I guess I should sanitize this as well
if (!empty($postID)) {
$command = "select * from $table_name where blogID = $postID";
$result = $db->query($command);
while ($data = $result->fetch_object()) {
$postID = $data->blogID;
echo "<TR><TD>".$postID."</TD>";
echo "<TD>".$data->author."</TD>";
echo "<TD>".$data->date."</TD>";
echo "<TD>".$data->entry."</TD></TR>\n";
}
$result->free();
}
else {
$command = "select * from $table_name";
$result = $db->query($command);
while ($data = $result->fetch_object()) {
$postID = $data->blogID;
echo "<TR><TD><a href='viewblog.php?postID=$postID'>".$postID."</a></TD>";
echo "<TD>".$data->author."</TD>";
echo "<TD>".$data->date."</TD>";
echo "<TD>".$data->entry."</TD></TR>\n";
}
$result->free();
}
$db->close;
?>

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