MySQL Select query recordset in an 2d PHP array - php

I want to fetch the record set in an PHP array. My select query is as below…......
SELECT sub_activity_alias
, a_s_month
, a_s_target
, a_s_target_no
, a_s_budjet
, achieved
, achieved_no
, expense
, a_s_target_type
FROM activity_planning
WHERE prj_id = 37
AND holder_id = 5
AND impl_1id = 0
AND impl_2id = 0
AND activity_id = 14
AND sub_activity_id = 109
AND acct_year = '2015-2016'
ORDER
BY FIELD(a_s_month,'Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar') ASC
When I run the query I am getting many rows with 9 column. I want an PHP 2d array where data will be stored. I want this php array data in my programming.

First read this article carefully. http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html
Especially "Connect to MySQL" part. After that you will really understand the concept of MySQL and PHP relation.
Then start learning PHP basics. If you don't know what an array or control statements are, you don't know enough.

Today I want to share you important topics that is mostly required while coding in PHP and MySQL. One important thing that we should keep in mind so that less hitting the database, it would increase the better performance of our web software applications. Unwanted access of database is harmful and resource misuse. If a record set of a select query is being used many time then we should keep in buffer it should be an array.
Please see the record set below. I want this in an php array so that I can use it as many time as I want without touching the database.
The select query is as below along with the code required.
<?php
/**** CONNECT TO THE DATABASE *****/
$host = "localhost"; $user= "root"; $pwd = "root1";
$dblink = mysql_connect($host,$user,$pwd);
if (!$dblink)
{
header("Location: db_error.php");
}
$database = "cinindia_ciiss";
mysql_select_db($database, $dblink) or die("\n Could not select database, Please try after some time..");
/**** WRITE YOUR SQL QUERY *******/
$select = "SELECT sub_activity_alias,
a_s_month,
a_s_target,
a_s_target_no,
a_s_budjet,
achieved,
achieved_no,
expense,
a_s_target_type
FROM activity_planning
WHERE prj_id = 37
AND holder_id = 5
AND impl_1id = 0
AND impl_2id = 0
AND activity_id = 14
AND sub_activity_id = 109
AND acct_year = '2015-2016'
ORDER BY FIELD(a_s_month,'Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar') ASC";
$queryResult= mysql_query($select);
/****** DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS *******/
$data_array=array();
/******* STORE ALL THE RECORD SETS IN THAT ARRAY ********/
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC)) {
array_push($data_array,$row);
}
mysql_free_result($queryResult);
/****** TEST TO SEE THE RESULT OF THE ARRAY ******/
echo '<pre>';
print_r($data_array);
echo '</pre>';
// FREE THE ARRAY DECLAREd WHEN USING COMPLETE .
mysql_close($dblink);
?>
Hope it will help you. If it help, please share in in social sites from, it is at the beginning of the topics.
Thanks.

Related

How to Display Joomla database table using native joomla 2.5 php objects

I am trying to display data from a MySQL database table using the native joomla PHP objects, however I can never get it to work right. It never displays any data.
I know how to display the data by connecting to the database the old fashion way, like below...
$con = mysqli_connect("localhost","xxxxxx_user10","$dbpass","xxxxxxx_final");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
//What is the base model
$sku = $finish;
// Select The Correct Table
$result = mysqli_query($con,"SELECT * FROM BAH_finish WHERE color_value='$sku' GROUP BY uniqueID ORDER BY uniqueID ASC");
$row = mysqli_fetch_array($result);
$finishname = $row['color_name'];
$finishtype = $row['color_type'];
However i'd like to display content like I have above, but by using the joomla native php objects, so iv'e created a sample php table with the following fields.....
| ID | Last | First | Address | City | State | ZIP
and tried to display it (ALL ROWS) / OR (ONE ROW) using the following joomla code.....but nothing happens....no matter how I try to switch it up or change out parts of the code....So my thinking is that i'm missing a fundamental part of how this should work....Thanks again for your help! Also please do not quote joomla 2.5 component tutorial from joomla.org...that is where I've gotten this code and IMO it lacks a lot of information.
<?php
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('Last', 'First', 'Address', 'City', 'State', 'ZIP')));
$query->from($db->quoteName('111testnames'));
$query->where($db->quoteName('Last') . $db->quote('buffet'));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
echo $results;
?>
You have to correct: $query->from($db->quoteName('111testnames'));
to $query->from($db->quoteName('#__111testnames'));
using #__ automatically adds the suffix of your table.
Another error that I could see is the where clause doesn't have have an operator. Please try to correct it to $query->where($db->quoteName('Last') ." = ". $db->quote('buffet'));.
In order to have a proper view of the results you have to use print_r($results); instead of echo $results; as there is an object array you have to display not a string.
Good Luck!

PHP SQL QUERY - Filtering with Query, multiple values for item

I have been learning PHP/MySQL for some time, have not learned that much, as I am focusing on iPhone Development as well as tackling my full time job as well.
I am building a mesaging client, using JSON to pull new messages and a chat windows.... The part I am having ap roblem with is getting information from my database. I am loking in this request to get all messages betwen to people (IE: FromUser and ToUser) and then display them in JSON, however I cannot display it in JSON properly for some reason.
Here is my example
<?php
$enduser = $_GET['usernameto'];
$enduser1 = $_GET['usernamefrom'];
$db = mydatabase;
$con = mysql_connect("localhost","admin","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db, $con);
$arr = array();
//Execute the query
$rs = mysql_query("SELECT * FROM messages WHERE touser = '$enduser' AND fromuser = '$enduser1'");
$rs1 = mysql_query("SELECT * FROM messages WHERE touser = '$enduser1' AND fromuser = '$enduser'");
// Add the rows to the array
while($obj = mysql_fetch_object($rs)) {
$arr = $obj;
}
// Add the rows to the array
while($obj1 = mysql_fetch_object($rs1)) {
$arr1 = $obj1;
}
echo '{"users":'.json_encode($arr).' '.json_encode($arr1).'}';
// echo ''.json_encode($arr).'';
mysql_close($con);
?>
Now this does show all messages for example FromUser= user1 ToUser= user2 and shows also Fromuser= user2 and toUser = User1. in two seperate JSON lists, but I would like for them to be pulled on one simple JSON list, if that can be done, that would be amazing, I know it must lay in my query section...
I also know their is tons of vulnerabilities and issues with my code that are not "clean" however for the time been this doesn't need to follow those methods, until I go and learn how to follow SQLi and Real Escape strings/injections....
Thanks :-)
The comment about learning about SQL Injection is correct but you would be able to get the messages in one query:
SELECT * FROM messages WHERE (touser = '$enduser' AND fromuser = '$enduser1') OR (touser = '$enduser1' AND fromuser = '$enduser')
This should select what you are looking for.
Your question is very unfocussed, but I think you just need to either concatenate the two result arrays with
$combined = array_merge($arr, $arr1);
Or change your query so it pulls both sets of data at once. But as Marc B say, you really need to get into the habit of avoid SQL injection, it's easy.

MySQL: multiple search/select queries at the same time?

I have a question on how to go about the next phase of a project I am working on.
Phase I:
create a php script that scraped directory for all .txt file..
Open/parse each line, explode into array...
Loop through array picking out pieces of data that were needed and INSERTING everything into the database (120+ .txt files & 100k records inserted)..
this leads me to my next step,
Phase II:
I need to take a 'list' of several 10's of thousand of numbers..
loop through each one, using that piece of data (number) as the search term to QUERY the database.. if a match is found I need to grab a piece of data in a different column of the same record/row..
General thoughts/steps I plan to take
scrape directory to find 'source' text file.
open/parse 'source file'.... line by line...
explode each line by its delimiting character.. and grab the 'target search number'
dump each number into a 'master list' array...
loop through my 'master list' array.. using each number in my search (SELECT) statement..
if a match is found, grab a piece of data in another column in the matching/returned row (record)...
output this data.. either to screen or .txt file (havent decided on that step yet,..most likely text file through each returned number on a new line)
Specifics:
I am not sure how to go about doing a 'multiple' search/select statement like this?
How can I do multiple SELECT statements each with a unique search term? and also collect the returned column data?
is the DB fast enough to return the matching value/data in a loop like this? Do I need to wait/pause/delay somehow for the return data before iterating through the loop again?
thanks!
current function I am using/trying:
this is where I am currently:
$harNumArray2 = implode(',', $harNumArray);
//$harNumArray2 = '"' . implode('","', $harNumArray) . '"';
$query = "SELECT guar_nu FROM placements WHERE har_id IN ($harNumArray2)";
echo $query;
$match = mysql_query($query);
//$match = mysql_query('"' . $query . '"');
$results = $match;
echo("<BR><BR>");
print_r($results);
I get these outputs respectively:
Array ( [0] => sample_source.txt )
Total FILES TO GRAB HAR ID's FROM: 1
TOAL HARS FOUND IN ALL FILES: 5
SELECT guar_nu FROM placements WHERE har_id IN ("108383442","106620416","109570835","109700427","100022236")
&
Array ( [0] => sample_source.txt )
Total FILES TO GRAB HAR ID's FROM: 1
TOAL HARS FOUND IN ALL FILES: 5
SELECT guar_nu FROM placements WHERE har_id IN (108383442,106620416,109570835,109700427,100022236)
Where do I stick this to actually execute it now?
thanks!
update:
this code seems to be working 'ok'.. but I dont understand on how to handle the retirned data correctly.. I seem to only be outputting (printing) the last variable/rows data..instead of the entire list..
$harNumArray2 = implode(',', $harNumArray);
//$harNumArray2 = '"' . implode('","', $harNumArray) . '"';
//$query = "'SELECT guar_num FROM placements WHERE har_id IN ($harNumArray2)'";
$result = mysql_query("SELECT har_id, guar_num FROM placements WHERE har_id IN (" . $harNumArray2 . ")")
//$result = mysql_query("SELECT har_id, guar_num FROM placements WHERE har_id IN (0108383442,0106620416)")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array($result);
$numRows = mysql_num_rows($result);
/*
while($row = #mysql_fetch_assoc($result) ){
// do something
echo("something <BR>");
}
*/
// Print out the contents of the entry
echo("TOTAL ROWS RETURNED : " . $numRows . "<BR>");
echo "HAR ID: ".$row['har_id'];
echo " GUAR ID: ".$row['guar_num'];
How do I handle this returned data properly?
thanks!
I don't know if this answers your question but I think you're asking about sub-queries. They're pretty straightforward and just look something like this
SELECT * FROM tbl1 WHERE id = (SELECT num FROM tbl2 WHERE id = 1);
That will only work if there is one unique value to that second subquery. If it returns multiple rows it will return a parse error. If you have to select multiple rows research JOIN statements. This can get you started
http://www.w3schools.com/sql/sql_join.asp
I am not sure how to go about doing a 'multiple' search/select statement like this?
With regards to a multiple select, (and I'll assume that you're using MySQL) you can perform that simply with the "IN" keyword:
for example:
SELECT *
FROM YOUR_TABLE
WHERE COLUMN_NAME IN (LIST, OF, SEARCH, VALUES, SEPARATED, BY COMMAS)
EDIT: following your updated code in the question.
just a point before we go on... you should try to avoid the mysql_ functions in PHP for new code, as they are about to be deprecated. Think about using the generic PHP DB handler PDO or the newer mysqli_ functions. More help on choosing the "right" API for you is here.
How do I handle this returned data properly?
For handling more than one row of data (which you are), you should use a loop. Something like the following should do it (and my example will use the mysqli_ functions - which are probably a little more similar to the API you've been using):
$mysqli = mysqli_connect("localhost", "user", "pass");
mysqli_select_db($mysqli, "YOUR_DB");
// make a comma separated list of the $ids.
$ids = join(", ", $id_list);
// note: you need to pass the db connection to many of these methods with the mysqli_ API
$results = mysqli_query($mysqli, "SELECT har_id, guar_num FROM placements WHERE har_id IN ($ids)");
$num_rows = mysqli_num_rows($results);
while ($row = mysqli_fetch_assoc($results)) {
echo "HAR_ID: ". $row["har_id"]. "\tGUAR_NUM: " . $row["guar_num"] . "\n";
}
Please be aware that this is very basic (and untested!) code, just to show the bare minimum of the steps. :)

PHP page to get results of MySQL query

I haven't a clue on how to write PHP but one of the sites I oversee uses it. I'd like to have a pie chart that automatically updates based on current data. I know how to write the HTML that will draw the chart but don't know how to get my MySQL statement to interact with the data. Here's the piece of code I want to run:
SELECT
pc.shortname Name,
Count(qa.factor) Count
FROM
stable_host pc,
stable_area pq,
stable_area_front qa
WHERE
pc.id = pq.host
AND pq.id = qa.area
AND ((pq.name='Signal1') OR (pq.name='Signal5'))
GROUP BY pc.shortname
ORDER BY pc.shortname
When I run this script, it gives me the following output:
Category1 62
Category2 53
Category3 35
Category4 38
My question is this: How do I get the output so it just shows the numbers, comma delimited? (Example: "62,53,35,38")
SELECT GROUP_CONCAT(count(qa.factor) SEPARATOR ',') count
I believe this is what you're asking.
You could use:
<?php
$dsn = '';
$username = '';
$password = '';
$query = "Paste your query here";
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->prepare($query);
} catch(PDOException $e) {
die("Could not connect to the database\n");
}
$results = $pdo->fetchAll();
if(count($results) > 0) {
$array = array();
foreach($queryResult as $row) {
$array[] = $row['Count'];
}
$commaDelimitedString = implode(',',$array);
} // No need for end PHP tag, they cause problems.
This:
- connects to database (or tries to)
- runs your query
- makes an empty array
- loops over your results
- takes the "Count" column and adds it to the end of the array
- compresses the array into a comma-delimited string.
Look here (http://wezfurlong.org/blog/2004/may/first-steps-with-pdo/ and http://www.electrictoolbox.com/php-pdo-bound-placeholders/) for some guidance on the usage of PDO and what you'll need to connect to the database (don't post those details, obviously)
It may look daunting, but just go one step at a time. If you have more questions just ask.

Extract all the data from a database

Hey, I am wondering how to extract the data from a table in a database onto a table in a page (users.php),
For example:
I want to be able to get all of the usernames and all the id's from my database onto a table.
So if I have in my database:
1 - Fred
2 - Frank
3 - Margret
It will see that I have them user's and id's in the database and print them onto a table.
Any help would be great,
Thanks.
Connect to your database. Host is the location, like localhost if its on your computer, or on the same server as your code. User and Password are self explanatory.
mysql_connect("host", "user", "pass");
The name of the database you want to access.
mysql_select_db("database");
The actual mysql query.
$result = mysql_query('SELECT `User_Name`, `User_ID` FROM TABLE');
Sort it into an array
while($temp = mysql_fetch_array($result)
{
$id = $temp['User_ID'];
$array[$id]['User_ID'] = $id;
$array[$id]['User_Name'] = $temp['User_Name'];
}
Turn the array into a table. (You could skip the last step and go right to this one.
$html ='<table><tr><td>User ID</td><td>User Name</td></tr>';
foreach($array as $id => $info)
{
$html .= '<tr><td>'.$info['User_ID'].'</td><td>'.$info['User_Name'].'</td></tr>';
}
echo $html . '</table>';
Or, the formatting you wanted
$html ='User Id - User Name';
foreach($array as $id => $info)
{
$html .= $info['User_ID'].' - '.$info['User_Name'].'<br>';
}
echo $html;
(For this answer, I will use the mysqli extension -- you could also want to use PDO ;; note that the mysql extension is old and should not be used for new applications)
You first have to connect to your database, using mysqli_connect (And you should test if the connection worked, with mysqli_connect_errno and/or mysqli_connect_error).
Then, you'll have to specifiy with which database you want to work, with mysqli_select_db.
Now, you can send an SQL query that will select all data from your users, with mysqli_query (And you can check for errors with mysqli_error and/or mysqli_errno).
That SQL query will most likely look like something like this :
select id, name
from your_user_table
order by name
And, now, you can fetch the data, using something like mysqli_fetch_assoc -- or some other function that works the same way, but can fetch data in some other form.
Once you have fetched your data, you can use them -- for instance, for display.
Read the pages of the manual I linked to : many of them include examples, that will allow you to learn more, especially about the way those functions should be used ;-)
For instance, there is a complete example on the page of mysqli_fetch_assoc, that does exactly what you want -- with countries insteand of users, but the idea is quite the same ^^
You can do something like the following (using the built-in PHP MySQL functions):
// assuming here you have already connected to the database
$query = "SELECT id,username FROM users";
$result = mysql_query($query, $db);
while ($row = mysql_fetch_array($result))
{
print $row["id"] . " - " . $row["username"] . "\n";
}
which will give you (for example):
1 - Fred
2 - Frank
3 - Margret
Where I've put the print statement, you can do whatever you feel like there eg put it into a table using standard HTML etc.

Categories