// This gets all the users that are active
// The limit is completely random, it is set to 2 for this example
$sql = <<<SQL
SELECT *
FROM `accounts`
WHERE active = 1
LIMIT 2
SQL;
if(!$getaccounts = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while ($row = $getaccounts->fetch_assoc()) {
$getid = $row["id"].',';
$getid = substr($getid, 0, -1);
$getusername = $row["username"];
$getpassword = $row["password"];
echo $getid;
echo $getusername."<br>";
echo $getpassword."<br>";
}
I know this hasn't been prepared but I am not using it for anything other than personal use.
I cannot understand why this is not getting rid of the last comma?
The output may be something like "32,14,"
And I want to get rid of the last comma by using the "substr" function.
But the output that that I get from $getid is "3214" (It gets rid of all the commas instead of just the last one.
I need it to output "32,14" but it's not working?
Could someone please tell me where I am going wrong?
If I do rtrim, it does the same thing and gets rid of all the commas! I am going to update something in the database using the ids, and that is why I need to get rid of the last comma
And I know this code is not secure, I am not using it for anything other than personal use and I was hoping someone could help me figure this out, I have been attempting it for days, it seems really simple and I bet I am missing something really stupid!
You have a XY Problem.
You want to concat all the id's into a comma-seperated string.
Here's a much easier solution by adding the items to an array and then implode().
<?php
// rest of your code
$ids = Array();
while ($row = $getaccounts->fetch_assoc()) {
$ids[] = $row["id"];
$getusername = $row["username"];
$getpassword = $row["password"];
echo $getusername."<br>";
echo $getpassword."<br>";
}
echo "ids: " . implode(",",$ids);
You should write code like..
$getid = "";
while ($row = $getaccounts->fetch_assoc()) {
$getid .= $row["id"].',';
}
$getid = rtrim($getid,',');
$q = " UPDATE accounts SET active = '0' WHERE id IN ($getid) ";
Related
Hi and thank you for your time,
I am having problems with the following code:
<?php
include './include/config.php';
$sqla = mysqli_query($conn, "SELECT * FROM sector");
while ($rowa = $sqla->fetch_assoc()) {
$codigo = $rowa['codigo'];
$sector = $rowa['sector'];
echo $sector. "<br>";
$sqlb = mysqli_query($conn, "SELECT * FROM cfamilia WHERE sector = '$codigo'");
while ($rowb = $sqlb->fetch_assoc()) {
$cfamilia= $rowb['cfamilia'];
echo $cfamilia. " - ";
}
}
?>
When I run the code, it only echo´s the first result of the first loop and then seems to get stuck on the inner loop, what am I doing wrong? All data in the database is available and correct.
I am probably doing it the wrong way, but I am no way a programmer.
Thanks for your help
I have searched to check if all data is correct and that all variables were clean.
I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}
I'm trying to return four records from my MySQL database but only the first record is being returned. I've searched but I'm unsure why this is. Can someone point me in the right direction?
<?php
session_start();
function displayImage($username){
$imageDate = $_POST['imageDate'];
$result = mysql_query("
SELECT
imageName
FROM
images AS i
INNER JOIN
users AS u ON i.userID = u.UserID
WHERE
u.username = '$username'
AND
i.imageDate = '$imageDate'
") or die(mysql_error());
//return a message to the users explaining ......
if (!isset($_POST['Submit'])) {
// this does nowt yet!!!
$output = "Nothing selected yet.";
}
else {
//This is a while loop to store the SQL results into ......
$row = array(mysql_fetch_assoc($result));
foreach ($row as $picName) {
$cam = $_POST['cam'];
$fullPath = $username . "/" . $cam . "/" . $picName['imageName'];
// $output = //this works fine
reset($images);
}
}
var_dump($row);
echo "<br />";
return $output;
}
?>
You should use loop to fetch result:
while ($row = mysql_fetch_assoc($result)) {
$cam = $_POST['cam'];
$fullPath = $username . "/" . $cam . "/" . $row['imageName'];
}
As others here have said, you need to use a while loop for this, I've tidied the code up a tiny bit and added a couple of other things for you to consider.
The actual reason for this is that when you use mysql_fetch_assoc it brings back one result resource and removes it from resources it has left to return. So if you just try and store it in an array, you get the first one in the array, and nothing else. When you use a while loop it works by basically saying "if mysql_fetch_assoc has something to give, then do the code inside the loop".
<?php
session_start();
function displayImage($username) {
// Also, as others have said, check out PDO, or MySQLi, as they
// both provide a better interface with MySQL an have better
// security features.
$username = mysql_real_escape_string($username);
$imageDate = mysql_real_escape_string($_POST['imageDate']);
$result = mysql_query("
SELECT
imageName
FROM
images AS i
INNER JOIN
users AS u ON i.userID = u.UserID
WHERE
u.username = '$username'
AND
i.imageDate = '$imageDate'
") or die(mysql_error());
//return a message to the users explaining
if (!isset($_POST['Submit'])) {
// this does nowt yet!!!
$output = "Nothing selected yet.";
} else {
$cam = $_POST['cam'];
$images = array(); // This is part of the "you could do something
// like" further down.
while ($row = mysql_fetch_assoc($result)) {
$fullPath = $username . '/' . $cam . '/' . $row['imageName'];
// $output = //this works fine
var_dump($row);
echo "<br />";
// Or you could do something like:
$images[] = $username . '/' . $cam . '/' . $row['imageName'];
// Then outside of this while loop you'd have all of your image
// paths stored in this $images array.
//
// It depends on how you want to handle outputting them.
}
}
return $output;
}
The comments in the code go through my main points.
I also moved that $cam = $_POST['cam'] from inside of the loop, to outside of it, as it doesn't need to go in the loop because it's value will always be the same, regardless of which loop item you're going over.
The way to use mysql_fetch_assoc or mysql_fetch_array is this:
while ($row = mysql_fetch_assoc($result)) {
// This is an example...
echo $row["id"];
echo $row["name"];
}
If you still need an explanation:
1. Why you got only one record??
When you declare:
$row=array(mysql_fetch_assoc($result));
This means that you get one record from the database, the mysql_fetch_assoc() method was run only once, so your method calls 1 row from the database table.
2. How to get this to work?
Like you have seen in the example given by others, use a while loop instead.
2.1 How does the loop work?
When you call:
while (<some command1 equates to true or false>) {<some command2>}
At first they run somecommand1. If it returns true, do some command2. After command2 has finished, run somecommand1 again. If it still true, do somecommand2 and so on... A nice example is the command you're using.
while ($row = mysql_fetch_assoc($result))
{
echo $row['fieldname1'];
echo $row['fieldname2'];
}
In this loop $row = mysql_fetch_assoc($result) is Somecommand1 as explained. This function returns a resource which equates to true if there is another row returned from the database. After one run through of the code within the while loop it skips onto the next row. Then it re-runs the mysql_fetch_assoc function. If there is still some record in the table that matches the query, this function will still do whatever is in your while loop.
If you need more examples, take a look at w3schools.com. I started PHP from there.
The other page that is the index page shows the catalog of the pizzashop. Each pizza is a hyperlink that passes the id to this page.
The core of my question is in the code that starts with the foreach loop. I would like to simply read out of the database based on the SELECT query at hand.
I know it is weird to put the query IN the loop but for now it is the only way I figured out how to loop through all the ids that are in the SESSION array.
I tried many things to output the return that the query is supposed to give, I fiddled around with the mysqli_stmt thing, all giving me numerous types of errors.
<?php
session_start();
require 'pizza_sc_fns.php';
require 'header.php';
#$pizzaId = $_GET['pizza_id'];
if (!isset($_SESSION['order']))
{
$_SESSION['order'] = array();
$_SESSION['items'] = 0;
$_SESSION['totalprice'] = 0.00;
}
if (isset ($_SESSION['order'][$pizzaId]))
{
echo $_SESSION['order'][$pizzaId]++;
echo "\$_SESSION['order'][\$pizzaId] is SET \n";
}
else
{
echo $_SESSION['order'][$pizzaId] = 1;
}
$conn = connect2db();
foreach ($_SESSION['order'] as $pizzaItem)
{
$query = "SELECT pizza_name FROM pizzas WHERE pizza_id = $pizzaItem";
$res = #$conn->query($query);
echo $res->fetch_assoc();
echo "<hr />";
//$query = mysqli_prepare($conn, "SELECT * FROM pizzas WHERE pizza_id=$pizzaItem");
//echo var_dump($query)."<br />";
//$stmt_exec = mysqli_stmt_fetch($query);
//print $pizzaItem."<br />";
}
?>
Destroy session >>
You are going to need to use a loop but you don't need to run the query for every iteration. You can use the in clause.
Your code would be something like
$query = 'Select pizza_name from pizzas where id in (';
foreach($_SESSION['order'] as $pizza_id) {
$query.= mysql_real_escape_string($pizza_id).', ';
}
$query= substr($query, 0, -2); //Get rid of the trailing comma and space
$query .= ')';
And you can run the query.
I would recommend that you use prepared statements though I'm not sure how to use them for an in statement.
Ok I have a table with a few fields. One of the fields is username. There are many times where the username is the same, for example:
username: bob
password: bob
report: 1
username: bob
password: bob
report: 2
I did a SQL statement to select * where username='bob'; but when I do the following PHP function, it will only return the last result:
$thisrow = mysql_fetch_row($result);
I need to get every field from every row. How should I go about doing this?
$mainsection="auth"; //The name of the table
$query1="select * from auth where username='$user'";
$result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); //do the query
$thisrow=mysql_fetch_row($result);
echo "Study: " . $thisrow[1] . " - " . $thisrow[5];
Sorry for such a dumb question. I can't seem to get the while loops of more than one field working for the life of me.
mysql_fetch_row fetches each row one at a time. In order to retrieve multiple rows, you would use a while loop like this:
while ($row = mysql_fetch_row($result))
{
// code
}
Use a loop, and use mysql_fetch_array() instead of row:
while($row = mysql_fetch_array($result)) {
echo "Study: " . $row[1] . " - " . $row[5];
// but now with mysql_fetch_array() you can do this instead of the above
// line (substitute userID and username with actual database column names)...
echo "Study: " . $row["userID"] . " - " . $row["username"];
}
I suggest you to read this:
http://www.w3schools.com/php/php_mysql_select.asp
It will give you an overview idea of how to properly connect to mysql, gather data etc
For your question, you should use a loop:
while ($row = mysql_fetch_row($result)){//code}
As said by htw
You can also obtain a count of all rows in a table like this:
$count = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM table"));
$count = $count["count"];
You can also append a normal WHERE clause to the select above and only count rows which match a certain condition (if needed). Then you can use your count for loops:
$data = mysql_query("SELECT * WHERE username='bob'");
for ($i = 0; $i
Also, mysql_fetch_array() is usually a lot easier to use as it stores data in an associative array, so you can access data with the name of the row, rather than it's numeric index.
Edit:
There's some kind of bug or something going on where my second code block isn't showing everything once it's posted. It shows fine on the preview.
I like to separate the DB logic from the display. I generally put my results into an array that I can call within the HTML code. Purely personal preference; but here's how'd I'd approach the problem: (I'd take the $sql out of the error message in production)
<?php
$sql="
SELECT *
FROM auth
WHERE username='$user';
";
$result = mysql_query($sql)
or die("Failed Query : ".mysql_error() . $sql); //do the query
while ($ROW = mysql_fetch_array($result,MYSQL_ASSOC)) {
$USERS[] = $ROW;
}
?>
HTML CODE
<? foreach ($USERS as $USER) { ?>
Study: <?=$USER['dbFieldName'];?> - <?=$USER['dbFieldName2'];?>
<? } //foreach $USER ?>
$qry=mysql_query(select * where username='bob');
if(mysql_num_rows($qry))
{
while($row=mysql_fetch_array($qry,MSQL_NUM))
{
echo $row[0]." ".$row[1]." ".$row[2]."<br>";
}
}