I am trying to upgrade my way to fetch data from sql from mysqli_query to fetchall.
$res = mysqli_query($db, "SELECT * FROM forum_index WHERE forum_over='yes'");
while ($arr = mysqli_fetch_assoc($res)) {
......
}
So when I use fetchAll() I'll get an array, Am I supposed to use foreach() then or is there a smarter way of doing this?
And to collect a single value from the DB this is the right way right?
$fid = (int)$_GET['id'];
$thread = $db->query("SELECT * FROM forum_threads WHERE f_id=".$fid)->fetch_array();
echo $thread['id'];
You don't need to use fetchAll() just because you're using PDO. If the query returns a large amount of data, this could slow things down because it has to collect it all into memory. You can use the same kind of loop as in your mysqli code:
$res = $pdo->query("SELECT * FROM forum_index WHERE forum_over='yes'");
while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
...
}
As to your second question, you should use a parametrized query, not substitute variables.
$stmt = $pdo->prepare("SELECT * FROM forum_threads WHERE f_id= :id");
$stmt->bindParam(':id', $_GET['id']);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
...
}
Related
I'm in the process of updating my old mysql database techniques to prepared pdo statements. I'm all good with while loops while($row = $result->fetch()) however how would I do the following with PDO prepared statements?
$sql = "SELECT * FROM table WHERE id=".$id;
$result = mysql_query($sql) or die(mysql_error());
$loop_count = mysql_num_rows($result);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = mysql_fetch_array($result);
echo $loop_row['field'];
}
I've tried this but with no joy:
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_count = $result->rowCount();
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = $result->fetch();
echo $loop_row['field'];
}
Thanks!
UPDATE: The reason for using a for loop instead of a while loop is the ability to paginate the results, otherwise I would just put LIMIT 7 on the end of the SQL query.
To properly count rows with PDO you have to do this -
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$rows = $result->fetch(PDO::FETCH_NUM);
echo $rows[0];
But you would be better off using LIMIT in your query if all you want to do is get a static number of results.
In addition you're making your loop overly complex, there is no need to test for a range in the for condition just set the static number unless you're doing something weird, like possibly pagination.
You can try it this way:
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_rows = $result->fetchAll();
$loop_count = count($loop_rows);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
echo $loop_rows[$row]['field'];
}
As requested by the OP, here's an example of PDO prepared statements using LIMIT and OFFSET for pagination purposes. Please note i prefer to use bindValue() rather than passing parameters to execute(), but this is personal preference.
$pagesize = 7; //put this into a configuration file
$pagenumber = 3; // NOTE: ZERO BASED. First page is nr. 0.
//You get this from the $_REQUEST (aka: GET or POST)
$result = $conn->prepare("SELECT *
FROM table
WHERE id= :id
LIMIT :pagesize
OFFSET :offset");
$result->bindValue(':id', $id);
$result->bindValue(':pagesize', $pagesize);
$result->bindValue(':offset', $pagesize * $pagenumber);
$result->execute();
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
This gives you the complete resultset of rows, limited to your required page. You need another query to calculate the total number of rows, of course.
What you could try is:
//Get your page number for example 2
$pagenum = 2;
//Calculate the offset
$offset = 7 * $pagenum;
//Create array
$data = array();
$result = $conn->prepare("SELECT * FROM table WHERE id= ? LIMIT 7 OFFSET ?");
$result->bind_param("ii", $id,$offset);
$result->execute();
$resultSet = $result->get_result();
while ($item = $resultSet->fetch_assoc())
{
$data[] = $item;
}
$result->close();
//echo resultSet you want
var_dump($data);
I will pass the query into this function query("SELECT * FROM table_name");
And the function is
public function query($sql) {
$resource = mysql_query($sql, $this->link_web);
if ($resource) {
if (is_resource($resource)) {
$i = 0;
$data = array();
while ($result = mysql_fetch_assoc($resource)) {
$data[$i] = $result;
$i++;
}
mysql_free_result($resource);
$query = new stdClass();
$query->row = isset($data[0]) ? $data[0] : array();
$query->rows = $data;
$query->num_rows = $i;
unset($data);
return $query;
} else {
return true;
}
} else {
trigger_error('Error: ' . mysql_error($this->link_web) . '<br />Error No: ' . mysql_errno($this->link_web) . '<br />' . $sql);
exit();
}
}
I want to add tenent_id = '1' in SELECT query also for INSERT query. Likewise I need to do it for UPDATE.
I want to bring the query like this
SELECT * FROM table_name WHERE tenent_id = 1 and user_id = 1
INSERT INTO table_name('tenant_id, user_id') VALUE('1','1')
UPDATE table_name SET user_id = 1 WHERE tenant_id = '1'
Can anyone give me the idea about how to insert tenant_id in select, insert and update
Thanks in advance
It's better practice to use the correct mysql functions rather than just a query function.
For example, if you want to cycle through many items in a database, you can use a while loop:
$query = mysql_query("SELECT * FROM table WHERE type='2'");
while($row = mysql_fetch_array($query)){
echo $line['id'];
}
This would echo all the IDs in the database that have the type 2.
The same principle is when you have an object, using mysql functions, you can specify how you want the data to return. Above I returned it in an array. Here I am going to return a single row as an object:
$query = mysql_query("SELECT * FROM table WHERE id='1'");
$object = mysql_fetch_object($query);
echo $object->id;
echo $object->type;
echo $object->*ANY COLUMN*;
This would return as:
1.
2.
Whatever the value for that column is.
To insert your data, you don't need to do "query()". You can simple use mysql_query($sql).
It will make life much easier further down the road.
Also, its best to run one query in a function, that way you can handle the data properly.
mysql_query("INSERT...");
mysql_query("UPDATE...");
mysql_query("SELECT...");
Hope this helps.
The simple answer is: just add the condition to your query. Call query("SELECT * FROM table_name WHERE tenant_id = 1 and user_id = 1").
If you're concerned about escaping the parameters you pass to the SQL query (which you should be!), you can either do it yourself manually, e.g.
$query = sprintf("SELECT * FROM table_name WHERE tenant_id = %d", intval($tenant_id));
query($query);
Or better use prepared statement offered by mysqli extension (mysql_query is deprecated anyway):
$stmt = $mysqli->prepare("SELECT * FROM table_name WHERE tenant_id = ?");
$stmt->bind_param("i", $tenant_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
// ...
}
If I still haven't answered your question, you can use a library to handle your queries, such as dibi:
$result = dibi::query('SELECT * FROM [table_name] WHERE [tenant_id] = %i', $id);
$rows = $result->fetchAll(); // all rows
The last option is what I would use, you don't need to write your own query-handling functions and get query parameter binding for free. In your case, you may utilize building the query gradually, so that the WHERE condition is not part of your basic query:
$query[] = 'SELECT * FROM table_name';
if ($tenant_id){
array_push($query, 'WHERE tenant_id=%d', $tenant_id);
}
$result = dibi::query($query);
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();
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
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);