How to? PHP & MySQL sortdata in a function - php

I am stuck in writing a PHP function. What I need to do is pass on about 10 - 12 ID into an array and then sort them by name in mysql database and then print some statements. I got this far where I manually add an ID number and it prints the information I need but at this point I have to sort the data before using those ID numbers.
Here is what I have done so far.
<?php
function print_software_info($id) {
$appinfo = "SELECT * FROM `appinfo` WHERE `id` = ".intval($id);
$rt = mysql_query($appinfo) or die(mysql_error("Could not retrieve database information"));
echo $rt['name'];
echo $rt['image'];
}
?>
<?php
print_software_info(217);
print_software_info(179);
print_software_info(8);
?>

with
$ids = array(13, 14, 250, ... );
First (optional for now, but keep in mine) make sure they're all integer (sanitize)
$ids = array_map('intval',$ids);
You need to build a query like this
$q = "SELECT * FROM `appinfo` WHERE `id` IN (". implode(',',$ids) ." ) ORDER BY name";
$result = mysql_query($q);
Then go through each rows..
while ($row = mysql_fetch_object($result)) {
echo $row->name;
echo $row->image;
}

Related

how to show multiple checkbox values from database in php

Please see database's image also
I want to show my checkbox values from database.
Example : my value is 25,26.
So, How can i display it one by one ?
such as,
-- 1st value is : 25.
--2nd Value is : 26.
my code:
$db = new mysqli("localhost","paroshic_paroshic","kxmcwQzLTrTR","paroshic_matri2018jl");
$sql = "select * from tbldatingusermaster order by userid desc";
$result = $db->query($sql);
while($data = $result->fetch_object()){
echo $data->education; //My value is 25,26
}
Thanks.
You can write html tags to page with echo, you know that. So basicly it will be something like this:
while($data = $result->fetch_object()){
echo '<input type="checkbox" name="check" value="'.$data->educationid.'">'.$data->educationid.'<br>';
}
I think the piece of the puzzle that you were looking for is perhaps explode to create an array of integers from the given string $data->educationid (ie: 25,26 )
$db = new mysqli("localhost","paroshic_paroshic","kxmcwQzLTrTR","paroshic_matri2018jl");
$sql = "select * from tbldatingusermaster order by userid desc";
$result = $db->query( $sql );
if( $result ){
while( $data = $result->fetch_object() ){
/* explode the string into little integers */
$ids=explode( ',', $data->educationid );
/* iterate through the pieces and generate an input[checkbox] element */
foreach( $ids as $id )printf('<input type="checkbox" name="UNKNOWN[]" value="%s" />',$id);
}
}

Fetch data from database and shift and add new value in an array

In database table I have Value column.Have more than 50 rows. Now in php, I have an fixed array of 10. at first 10 rows will be fetched from database and stored into array. When array will be full, and 11th value will try to insert into array , 0th value will move and 11th value will insert into the array. For example like QUEUE process.
At first it will show
[[0,17.9999],[1,13.898],...[9,16.98]]
then [0,17.9999] will move and [10,11.88] will insert and it will print as follow
[[1,13.898],.......[9,16.98],[10,11.88]]
then
[2,17.84],......[10,11.88],[11,999]]
and so on..
How can I represent it in php?
Here is my code:
<?php
include("md.php");
$sql = "SELECT * from datatable";
$result =oci_parse($conn, $sql);
$r=oci_execute($result);
$arr = array();
$i=0;
while($row = oci_fetch_array($stid,OCI_ASSOC)){
$arr[] = array_shift(array($i++, (float)$row['VALUE']));
}
echo json_encode($arr);
?>
Please help.
If you always have 10 keys in array, try
$arr=array_slice($arr,1,9);
$arr[]=$row['VALUE'];
instead
$arr[] = array_shift(array($i++, (float)$row['VALUE']));
Note, It will be correct, when you already have array with 10 items.
See example below
$arr = array(1,2,3,4,5,6,7,8,9,10);
echo json_encode($arr)."<br>";
$con = mysqli_connect('127.0.0.1','app_user2','qwe123','test');
$select="select id from adv where id > 300 and id < 312;";
$res = mysqli_query($con, $select);
while ($row=$res->fetch_assoc()) {
$arr=array_slice($arr,1,9);
$arr[]=$row['id'];
echo json_encode($arr)."<br>";
}
In browser it would represented as
[1,2,3,4,5,6,7,8,9,10]
[2,3,4,5,6,7,8,9,10,"301"]
[3,4,5,6,7,8, 9,10,"301","302"]
[4,5,6,7,8,9,10,"301","302","303"]
[5,6,7,8,9,10,"301","302","303","304"]
[6,7,8,9,10,"301","302","303","304","305"]
[7,8,9,10,"301","302","303","304","305","306"]
[8,9,10,"301","302","303","304","305","306","307"]
[9,10,"301","302","303","304","305","306","307","308"]
[10,"301","302","303","304","305","306","307","308","309"]
["301","302","303","304","305","306","307","308","309","310"]
["302","303","304","305","306","307","308","309","310","311"]
If I understand, on 50 entries you'll get only 10, and the 11th is pushing away the 1st value of the array... It's like getting the last 10 resulsts, don't you think?
By admitting that your table has an auto-incremented 'id' field :
<?php
include("md.php");
// I've changed your SQL query by adding a reverse sort
// on the 'id' field and put a limit of 10 entries
$sql = "SELECT * from datatable ORDER BY id DESC LIMIT 0,10";
$result =oci_parse($conn, $sql);
$r=oci_execute($result);
$arr = array();
$i=0;
while($row = oci_fetch_array($stid, OCI_ASSOC)){
$arr[] = (float)$row['VALUE'];
}
echo json_encode($arr);
?>
I haven't tested this snippet but it should work fine ;)
EDIT : Please ignore if Ilya's answer is what you want to do D:

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 mySQL get table headers function

I'm trying to build a PHP function that allows me to have an array of the headers of MySQL database for finding a particular field.
function table($tablename,$id) {
$post = mysql_query("SELECT * FROM $tablename WHERE ID = '$id'");
}
How would I then output the table headers as effective miniature queries for the row in question.
eg. $post->title, $post->timestamp, $post->field4
You need MySQLi or PDO_MySQL, but in your case:
while ($row = mysql_fetch_assoc($post)) {
echo $row['title'];
}
Documentation
Remember that the use of mysql_* function is discouraged.
A simple PHP Script to fetch the field names in MySQL:
<?php
$sql = "SELECT * FROM table_name;";
$result = mysql_query($sql);
$i = 0;
while($i<mysql_num_fields($result))
{
$meta=mysql_fetch_field($result,$i);
echo $i.".".$meta->name."<br />";
$i++;
}
?>
OUTPUT:
0.id
1.todo
2.due date
3.priority
4.type
5.status
6.notes
Hope this helps! Taken from php.net documentation.
How about mysql_fetch_assoc($post)?
To get all field names int a seperate array:
$post = mysql_fetch_assoc($post);
$fields = array();
foreach($post as $title => $value){
$fields[] = $title;
}
You can use this in a while loop to go through all rows and get theri field values(as well as their names):
while($p = mysql_fetch_assoc($post)){
$title = $p['title'];
$timestamp = $p['timestamp'];
//And so on...
}
Edit: And Pierpaolo is right, you should use another mysql implementation as the old one is gonna be removed in PHP 5.5/5.6 or a bit later...
You can get just the column names by executing this:
DESCRIBE `MyTable`;
It will return a result set that contains Field, Type, Key, etc.
$query = mysql_query("DESCRIBE `MyTable`");
while($result = mysql_fetch_assoc($query)) {
echo $result['Field'] . "\n";
}

Echo the results of query based on its index

This is pretty basic but I can't seem to get it to work
I have this query
$people = "SELECT name FROM people";
$people = mysql_query($people) or die(mysql_error());
$row_people = mysql_fetch_assoc($people);
$totalRows_people = mysql_num_rows($people);
I can echo the first result of this query with
<?php echo $row_people['name']; ?>
I could also create a loop and echo all the results.
But I really want to echo the results individually based on its index.
I have tried this, but it does not work.
<?php echo $row_people['name'][2]; ?>
Thanks for your help.
You can fetch them by their index using a WHERE clause.
$people = sprintf("SELECT name FROM people WHERE index='%d'", $index);
If you want to query all rows, you could store them into an array while looping over them:
$people = "SELECT name FROM people";
$people = mysql_query($people) or die(mysql_error());
$totalRows_people = mysql_num_rows($people);
$rows_people = array();
while($row_people = mysql_fetch_assoc($people))
{
$rows_people[] = $row_people;
}
You might want to add the primary key to the returned fields and use it as the array index probably.
You can ORDER them by their index and then use a loop.
$people = "SELECT name FROM people ORDER by index";
You can use mysql_data_seek on the result object to seek to a particular row. E.g., to get the name value from row 2:
mysql_data_seek($people, 2);
$row_people = mysql_fetch_assoc($people);
echo $row_people['name'];
If you're doing this a lot it will be easier to gather all the rows together in a single array at the start:
$data = array();
while ($row = mysql_fetch_assoc($people)) $data[] = $row;
This way you can fetch any cells in the results trivially:
echo $data[2]['name'];

Categories