This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do i “echo” a “Resource id #6” from a MySql response in PHP?
I am looking for the result out of a query, but it keeps giving me resource id #3.
The following is my code.
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
print_r($typeResult);
What step am I missing here?
You need to fetch the result. All you're doing is sending the query.
Be aware that if you are writing new code, you should use mysqli_ or PDO functions as your query is vulnerable to SQL injection and mysql_ functions are being deprecated. Hesitantly, below is a sample for mysql_fetch_assoc.
<?php
$sql = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row[sellingid];
}
mysql_free_result($result);
?>
Reference
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
$row = mysql_fetch_array($typeResult);
print_r($row);
More clear hint - use MySQLi class/functions, read this:
http://lt1.php.net/manual/en/mysqli-result.fetch-assoc.php
or if you like OOP approach more then
http://lt1.php.net/manual/en/mysqli-result.fetch-object.php
You are not actually fetching the results of your query. Below are two examples that use WHILE loops to fetch the results as rows. You can then grab the column values and work with them.
Incorrect and depreciated method, but working:
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
// for each row
while ($row = mysql_fetch_array($typeResult)) {
// grab the columns
$value = $row['column_name'];
}
I would recommend using MySQLi or PDO like to following (MySQLi):
$mysqli_connection = new mysqli("hostname", "username", "password", "database");
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$res = $mysqli_connection->query($type);
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$value = $row['column_name'];
}
$res->free();
$mysqli_connection->close();
Related
I'm trying to convert some old php mysql code into PDO format but am stuck. I've looked at other posts on here but can't quite figure it out.
This is the old code:
<?php
if (isset($_POST['query'])) {
// Connect to database
mysql_connect("localhost", "xxxxx", "xxxxx");
mysql_select_db("xxxxx");
// Retrieve the query
$query = $_POST['query'];
// Search the database for all similar items
$sql = mysql_query("SELECT * FROM articles WHERE title LIKE '%{$query}%'");
$array = array();
while ($row = mysql_fetch_assoc($sql))
{
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
}
?>
And this is what I've managed to do but think there's something wrong in the "while" part.
<?php
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// Retrieve the query
$query = $_POST['query'];
// Search the database for all similar items
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
while ($row = $sql->fetchAll()) {
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
}
?>
You are trying to call fetchAll on "sql" which is a string.
Now, you could use query but i suggest you to use prepare instead (for security reason, because you insert POST data).
$q = $conn->prepare("SELECT * FROM articles WHERE title LIKE CONCAT('%', ? ,'%')");
$q->execute(array($query));
// result contains all returned data
$result = $q->fetchAll();
// or row by row
while($row = $q->fetch())
From PHP.net
foreach ($conn->query($sql) as $row) {
Try somehing like this:
<?php
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// Retrieve the query
$query = $_POST['query'];
//Build Query - Search the database for all similar items
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
$sth = $conn->query($sql);
$result = $sth->fetchAll();
foreach($result as $row){
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
}
?>
=========Updated Answer========
//Better alternative
$query = $_POST['query'];
$sql = "SELECT * FROM articles WHERE title LIKE CONCAT('%', ? ,'%')";
$sth = $con->prepare($sql);
$sth->bind_param("s", $query);
$sth->execute();
$result = $sth->fetchAll();
foreach($result as $row){
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
PS: Best practice is to stick with prepared statements and execute for increased security.
Try to run this:
$rows = $conn->prepare("SELECT * FROM articles WHERE title LIKE ?")->execute(array('%'.$query.'%'))->fetchAll();
while($row = $rows->fetch()) {
// TODO: Parse the rows
}
Also, try not to use * in your queries, that's not the best practice, it is better to use a column list instead separated by commas, as you do not necessary need to load the values of all columns. select * is less scalable and it might be the source of security vulnerabilities, like accidentally loading the inappropriate column and passing its value to the inappropriate place.
I want to search in a database table for a particular word and want to retrieve a text from other column in the same row and there may be more than one rows where that word may exist, so i want all those rows where that word is.
i am using this code
$found = 'world';
$sql = "SELECT file_id FROM hello WHERE $field = '$found'";
$result = mysql_query( $sql);
$row = mysql_fetch_array($result);
while($row)
{
echo $row['file_id'];
}
so my problem here is in database table i have only 5 rows and there are only 2 possible file_id to be printed after the code, but this while loop goes to infinite.
Thanks in advance
The quick fix is this:
$found = 'world';
$sql = "SELECT file_id FROM hello WHERE field = '$found'";
$result = mysql_query( $sql);
while($row = mysql_fetch_array($result)) {
echo $row['file_id'];
}
But there are quire a lot other things to be corrected:
use the mysqli extension, the mysql extension is deprecated
you should use prepared statements to prevent sql injections
you must add error checking and handling
...
if you are starting a project use PDO
$db new PDO('mysql:host=localhost dbname=foo', 'user', 'password');
$sql = 'SELECT file_id FROM hello WHERE field = ? ';
$stmt = $db-prepare($sql);
$stmt->bindValue(1, $word);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $item){
echo $item['key'];
}
I have a table called sales_product with columns
sales_product_id, sales_id, type, class, age
I have a query in php saying
$sql = "SELECT * from sales_product WHERE sales_id = " . $_GET['sales_id];
Suppose this query returns two rows.
$result = mysql_query($sql);
How do I loop through this result and save in an array so that later on I can retrieve data like
echo $sales_product[$i]['sales_product_id'];
echo $sales_product[$i]['sales_product_id'];
........
Do mysql_fetch_assoc in while loop:
$result = mysql_query($sql);
$rows[] = array();
while ( $row = mysql_fetch_assoc($result) ) {
echo $row['sales_product_id'];
$rows[] = $row;
}
var_dump($rows);
Use mysql_fetch_assoc
while ($row = mysql_fetch_assoc($result)) {
echo $row["sales_product_id"];
}
Try this,
$result = mysql_query($sql);
while ( $row = mysql_fetch_assoc($result) ) {
echo $row['columnName'];
}
Use mysql_fetch_array() if u need with index
check this one.
$sql="SELECT sales_product_id, sales_id, type, class, age From sales_product";
$sales= $db->query($sql);
while($sale = $db->fetchByAssoc($sales))
{
echo $sales['sales_product_id'];
echo $sales['type'];
// here instead echo uyou will add data in your array
}
Take a look at
mysql_fetch_array();
Note
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_fetch_array()
PDOStatement::fetch()
Something like this should work, this will give you the format you requested (untested):
while($row = mysql_fetch_assoc($result)) {
$sales_product[] = $row;
}
Since mysql_ has been declared deprecated so i am going to answer your question with
mysqli_* extension
//Prepare an SQL statement for execution
$stmt = $mysqli->prepare("SELECT * from sales_product WHERE sales_id = ?");
//bind parameter to the prepared statement
$stmt->bind_param("i", $_GET['sales_id]);
//execute it
$stmt->execute();
//store the result
$result = $stmt->get_result();
//loop through the result set
while ($myrow = $result->fetch_assoc())
{
$salesIds[] = $myrow["sales_product_id"];
}
For more information please refer to php documentation.
Thanks
This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 6 months ago.
I want to select only unique values with php/mysql.
I can do it with many line, but I forget how to do it without while... :)
Thanks a lot.
Here is the code that I want to do without while.
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
while($row = mysql_fetch_array($result_1m))
{
/* Get the data from the query result */
$date1_1m = $row["date1"];
$date2_1m = $row["date2"];
}
mysql_fetch_assoc + SELECT with DISTINCT
I'm not sure I understand your question, but here's what I think you want to do :
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
list($date1_1m, $date2_1m) = mysql_fetch_row($result_1m);
Note that this will only get the first row from the result set (just as if you LIMIT 1)
like this?
$dbresult = mysql_query("SELECT DISTINCT field FROM table");
$result = array();
while ($row = mysql_fetch_assoc($dbresult))
{
$result[] = $row;
}
This gets you all unique values from "field" in table "table".
If you really wish to avoid the while loop, you can use the PHP PDO objects, and in particular call the PDO fetchAll() method to retrieve the complete results array in one go. PDO fetchAll() documentation
$db = new PDO('dblib:host=your_hostname;otherparams...');
$db->query("SELECT DISTINCT col FROM table");
$results = $db->fetchAll();
// All your result rows are now in $results
Heres how I do it and Json encode after. This will ensure it will encode only UNIQUE json Values (Without duplicates) as an example
$tbl_nm = "POS_P";
$prod_cat = "prod_cat";
//Select from the POS_P Table the Unique Product Categories using the DISTINCT syntax
$sql = "SELECT DISTINCT $prod_cat FROM $tbl_nm";
//Store the SQL query into the products variable below.
$products = mysql_query($sql);
if ($products){
// Create an array
$rows = array();
// Fetch and populate array
while($row = mysql_fetch_assoc($products)) {
$rows[]=$row;
}
// Convert array to json format
$json = json_encode(array('Categories'=>$rows));
echo $json;
}
//Close db connection when done
mysql_close($con);
?>
That is very easy, take out the while, like below
$row = mysqli_fetch_assoc($result);
$date1_1m = $row["date1"];
I can find lots of tutorials showing you how to load an array into a database field but can't seem to figure out how to pull each entry in a field into an array as seperate items. Seems simple enough just can't get it to work, any help?
If using the modern PDO library, use the PDOStatement->fetchAll() function with the fetch_style parameter set to PDO::FETCH_COLUMN.
Based on a sample from that page:
$sth = $dbh->prepare("SELECT field FROM dbtable");
$sth->execute();
$array = $sth->fetchAll(PDO::FETCH_COLUMN);
If using the old MySQL API (not recommended, example omits error checking)
$array = array();
$result = mysql_query("SELECT field FROM dbtable");
while ($row = mysql_fetch_row($result)) {
$array[] = $row[0];
}
mysql_free_result($result);
$big_2_dimensional_array_of_data;
foreach ($big_array_of_data as $row) {
$query = "INSERT INTO table_name (field1, field2, ...) VALUES($row[0], $row[1], ...)
mysql_query($query);
}
Something like that I think
after reading his question a few times, i guess what he wants to do is something like this:
$query = "SELECT field1, field2, ... fieldn FROM table;";
$r = mysql_query($query,$conn);
$row = mysql_fetch_assoc($r);
i'm still not quite sure what it is he exactly wants...
My interpretation of this question is that the questioner has inserted a number of rows into a table, and isn't sure how to handle getting them out other than one at a time. (It's possible that the question might also be referring to data serialized and then stuck into a single field... but I hope not!)
So, here's how to get multiple rows:
$query = "SELECT field1, field2, ... fieldn FROM table;";
$r = mysql_query($query,$conn);
$data = array();
while($row = mysql_fetch_assoc($r)) {
$data[] = $row;
}
You'd now have all the rows returned by your query in $data, so something like this would work to access it: $data[2]['field1']
The examples below assume your SELECT statement is stored in $select and your connection is stored in $db. A two-dimensional array of the results is stored in $rows afterward.
If you're using mysql (for mysqli procedures, just replace mysql_ with mysqli_):
$result = mysql_query($select, $db);
$rows = [];
while ($row = mysql_fetch_assoc($result) {
$rows[] = $row;
}
Using mysqli classes:
$result = $db->query($select);
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$result->close()
Using PDO:
$stmt = $db->query($select);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);