PHP query get result from select - php

hi I need help with 2 mysql queries I am working on. I need to get data from first query and use it in second query.
First query (get different extension for domains)
$resultExt = mysql_query("SELECT * FROM extension”) or die(mysql_error());
while($rowExt = mysql_fetch_array( $resultExt )) {
$extDom = $rowExt[‘ext’];
$postDom = 'Domain_’ . $extDom ;
$dom_to_show .= '$rowCart[$postDom];';
}
and I get my list of domain extensions
$Domain_com = $rowCart[‘Domain_com’]; $Domain_net = $rowCart[‘Domain_net’];
and so on
Second Query (get data from cart)
then I need to get data from cart table
$showCart = mysql_query("SELECT * FROM cartlist where Session = '".$session."' ORDER BY ID DESC") or die(mysql_error());
while($rowCart = mysql_fetch_array( $showCart )) {
//here i need to get variable like $Domain_com = $rowCart['Domain_com’];
//if I use echo $dom_to_show; or $dom_to_show; I get no result
}
what do I need to put inside the second while to get results from query?
thanks

The echo should echo out a result, i have added an array that will get all the data in the row and output it after it has ran. This will help you see if there is any data returned from the query.
$showCart = mysql_query("SELECT * FROM cartlist where Session = '".$session."' ORDER BY ID DESC") or die(mysql_error());
while($rowCart = mysql_fetch_array( $showCart )) {
//here i need to get variable like $Domain_com = $rowCart['Domain_com’];
//if I use echo $dom_to_show; or $dom_to_show; I get no result
echo $rowCart['Domain_com'];
//or
$array[] = $rowCart;
}
echo "<pre>";
print_r($array);
also
$rowCart['Domain_com'];
was set to
$rowCart['Domain_com’];
which is wrong.

Related

Multiple PHP dynamic variables displaying other dynamic variable values

I am generating dynamic variables like so:
$testPMA = '';
$result = mysql_query("SELECT * FROM site_pma") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
${$testPMA.$row['id']} = $row['value'];
}
$testLocation = '';
$result = mysql_query("SELECT * FROM site_location") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
${$testLocation.$row['id']} = $row['value'];
}
then I try displaying them like so:
if(isset(${$testPMA.$row_bom_lines['pma']})) echo ${$testPMA.$row_bom_lines['pma']};
The first one returns correctly. The next column and any after always take their id number for the dynamic variable, but only generate PMA. They never update to show Location or any other one I have created. I even tried mysql_free_result($result); after each one. How do I get the dynamic variable to display each of their own vs displaying the same table information for each column, just with an updated id number?

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;
?>

Extract a specific value from this data type

I'm using this script to get data from a database
$sql = "SELECT * FROM items WHERE catid = 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo $row['extra_fields'];
}
The output is:
[{"id":"1","value":"johndoe"},{"id":"2","value":"marydoe"}]
I want to extract/print only the value corresponding to "id":"1" (that in this case is 'johndoe'). I'm not able to extract it from the above data type.
To read JSON in PHP use
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields'];
// Do something with $array['id']
}
Did you realise you can directly go for that data in MySQL?
SELECT value FROM items WHERE id = 2;
edit:
Basically your query is
SELECT comma-separated column names or star for all, use only what you really need to save bandwidth, e.g. SELECT id, value
FROM table-name, e.g. FROM mytable
WHERE columnname = desired value, e.g. WHERE id = 2
You want to query only the required columns in the required rows. Imagine one day you would have to parse 1 million users every time you want to get an id... :)
The output is JSON. Use PHP's json_decode function.
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields']);
foreach($array AS $item) {
echo $item['id'];
}
}
Currently this is the code that fits my needs:
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields']);
$value = $array[0]->value;
}
You should do it in the mysql query part. For example, set the ID = 1 in the query.

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'];
}

SQL query is only retrieving first record

I have a query which is designed to retireve the "name" field for all records in my "tiles" table but when I use print_r on the result all I get is the first record in the database. Below is the code that I have used.
$query = mysql_query("SELECT name FROM tiles");
$tiles = mysql_fetch_array($query);
I really cant see what I have done wrong, I have also tried multiple searches within google but I cant find anything useful on the matter at hand.
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['age'];
echo "<br />";
}
?>
'mysql_fetch_array'
Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
This means that it returns array (contains values of each field) of A ROW (a record).
If you want other row, you call it again.
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
// Do something with $row
}
Hope this helps. :D
Use "mysql_fetch_assoc" instead of "mysql_fetch_array".
$query = mysql_query('SELECT * FROM example');
while($row = mysql_fetch_assoc($query)) :
echo $row['whatever'] . "<br />";
endwhile;
I believe you need to do a loop to invoke fetch array until it has retrieved all the rows.
while ($row = mysql_fetch_array($query) ) {
print_r( $row );
}

Categories