I'm trying to echo out every single thing in a table from sql, my code is as follows
$stmt = $link->prepare("SELECT * FROM articles");
$stmt->execute();
$stmt->store_result();
if (mysqli_stmt_num_rows($stmt) >= 1) {
$result = mysqli_stmt_get_result($stmt); //get result object
while ($row = mysqli_fetch_assoc($result)){ //get associative array
$news = $row['title'];
}
}
It doesn't work, returning as mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given
I've done my research but literally nothing works :(
You don't need to use prepared statements for this SELECT query as you aren't specifying anything WHERE.
$query = 'SELECT * FROM articles';
if ($result = $link->query($query)) {
while ($row = $result->fetch_assoc()) {
$news = $row['title'];
}
}
For a really good in-depth answer check this out: https://stackoverflow.com/a/11575617/1427345
Related
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)) {
...
}
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);
In the below code when I pass $id_num to check the id field in database it accepts but when I want to pass user id to check with database it shows the following error;
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in line no 12
Can anyone tell me where I'm going wrong.
code:
if(isset($_POST['user_mail']) && isset($_POST['user_pass']))
{
$var_1=$_POST["user_mail"];
$var_2=$_POST["user_pass"];
$result = mysqli_query($con,"SELECT * FROM jsrao_db2 WHERE user_mail=$var_1");
while($row = mysqli_fetch_array($result))
{
if(($row['user_mail']==$var_1) && ($row['user_pass']==$var_2))//compare user name and password with database value
echo "Welcome";
else
echo "Try Again";
}
change your query
$result = mysqli_query($con,"SELECT * FROM jsrao_db2 WHERE user_mail=$var_1");<br>
should be
$result = mysqli_query($con,"SELECT * FROM jsrao_db2 WHERE user_mail='$var_1'");<br>
user_mail is an string so enclose $var_1 in '$var_1'
Use Prepared Statements for cleaning up your code:
$result = false;
$stmt = $con->prepare("SELECT * FROM jsrao_db2 WHERE user_mail=?");
$stmt->bind_result($result);
$result = $stmt->bind_param("s", $var_1)->execute();
if ($result) {
//work with $result
}
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 recently implemented PDO and noticed that my query results lacked the first row. That's probably because fetchColumn() retrieves the first row and moves the pointer to the second row so that the while() loop starts at row 2. Is that correct? If so, how can I avoid that and improve the following code block?
$STH = $DBH->prepare("SELECT * FROM users");
$result = $STH->execute();
if (!$result)
{
return false;
}
elseif($STH->fetchColumn()>0)//counterpart of mysql_num_rows()
{
while ($row = $STH->fetch())
{
...
}
}
}
Is that correct?
Yes. Also, fetchColumn() is not an equivalent for mysql_num_rows(). Instead, fetchColumn() retrieves the indexed column value (defaulting to index 0) of the current row and as assumed, advances the cursor.
If you need a count of the number of rows returned in your query, I suggest you first issue a SELECT COUNT(1) ... query with the same conditions, using fetchColumn() to return the count.
See example #2 on this manual page - http://www.php.net/manual/en/pdostatement.rowcount.php
For example
$stmt = $DBH->query('SELECT COUNT(1) FROM users');
// using a straight PDO::query() call as a prepared statement would be
// overkill for these queries
if ($stmt->fetchColumn() == 0) {
return false;
}
$stmt = $DBH->query('SELECT * FROM users');
while ($row = $stmt->fetch()) {
...
}
After googling around I came up with this solution:
$STH = $DBH->prepare("SELECT * FROM users");
if(!$STH)
{
$error = $DBH->errorInfo();
}
else
{
$result = $STH->execute();
if($result===false)
{
return false;
}
else
{
$rows = $STH->fetchAll(PDO::FETCH_ASSOC);
if(count($rows) > 0)
{
foreach ($rows as $row)
{
...
}
}
}
}
}