PHP Query response to string - php

I'm running a PHP query which returns several rows / columns. (Im returning the columns: name, quantity, unit, producer, notes) * X rows (depending on how many rows were found in the database).
$sql = "SELECT products.name, products.unit, lists.quantity, lists.producer, lists.notes FROM lists,products WHERE lists.familyid ='$familyid' AND lists.productid = products.id ";
$sqlmessage=mysql_query($sql);
Now i would like to arrange this response into a STRING, in order to email it using mail($to,$subject,$message,$headers).
Im trying to use the following function, however im not getting the correct list but rather alot of " fetchColumn(name) "
The Broken function:
for ($i=0; $i<mysql_num_rows($sqlmessage); ++$i){
while ($row = mysql_fetch_array($sqlmessage)){
$name = $row->fetchColumn($i);
$message .= "$name";
$message .= ", ";
}
}
What do i need to change to get the correct information out ? Been searching for a day now and trying different things without any success.'

You are using two loops (i dont know why) and object to mysql_fetch_array() .Do you mean something like this?:
while($row = mysql_fetch_array($sqlmessage))
{
$name = $row['name'];
$message .= $name;
$message .= ", ";
}

Related

SQL query not working but works in PHPMyAdmin

I have a web application and I'm trying to modify one of the queries. The query fetches information (from a table named voyage_list) and returns various fields.
I want to modify the query so that it is based on certain filters the user applies (which will be placed in the URL).
I can't get the query to work in the web application, but if I copy the query and execute it directly within PHPMyAdmin, it works fine.
$vesselFilter = $_GET['vesselFilter'];
$vesselArray = explode(',', $vesselFilter);
$arrayCount = count($vesselArray);
$sqlExtend = ' status = 1 AND';
foreach ($vesselArray as $value) {
$i = $i + 1;
$sqlExtend .= " vesselID = '$value'";
if ($i < $arrayCount){
$sqlExtend .= " OR";
}
}
$newQuery = "SELECT * FROM voyage_list WHERE" . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
I appreciate the above is pretty messy, but it's just so I can try and figure out how to get the query to work.
Any help would be greatly appreciated!
Thanks
That query probably doesn't return what you think it does. AND takes precedence over OR, so it will return the first vessel in the list if the status is 1, and also any other vessel in the list, regardless of status.
You'd do better to create a query with an IN clause like this:
SELECT * FROM voyage_list WHERE status = 1 AND vesselID IN(8,9,10)
Here's some code to do just that:
$vesselFilter = $_GET['vesselFilter'];
// Validate data. Since we're expecting a string containing only integers and commas, reject anything else
// This throws out bad data and also protects against SQL injection.
if (preg_match('/[^0-9,]/', $vesselFilter)) {
echo "Bad data in input";
exit;
}
// filter out any empty entries.
$vesselArray = array_filter(explode(',', $vesselFilter));
// Now create the WHERE clause using IN
$sqlExtend = 'status = 1 AND vesselID IN ('.join(',', $vesselArray).')';
$newQuery = "SELECT * FROM voyage_list WHERE " . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
var_dump($query);

PHP MySQL Where clause isn't working

I have a database like which has multiple columns and when querying it with a WHERE clause it won't get any results.
Here is the code I am using :
$columns = $_GET['var'];
$where = $_GET['where'];
$checkValue = $_GET['checkValue'];
$userInput = $_GET['userInput'];
$query = "SELECT ";
foreach($columns as $val)
$query .= "$val, ";
$query .= "FROM Email";
if($where === "yes")
$query .= " WHERE $checkValue = '$userInput'";
$columns is multiple checkboxes for the user to select which columns they wish to see. It works perfectly except when adding the where clause. When I've been testing it I made sure that the it was exactly the same as in the database. Also the $checkValue is a dropdown list which values are exactly the same as in the database. Also just to note later on I edit the query so the last comma is removed.
To print it out I use :
while($c = mysqli_fetch_assoc($results)){
foreach($columns as $val){
$header = ucwords($val);
echo "<b>$header</b><br>";
echo $c[$val]."<br>";
}
echo "-------------------------------<br>";
}
This is the query that is outputted when not using the where clause and works:
SELECT date, mediatype FROM Email
And here is the query that doesnt work:
SELECT date, mediatype FROM Email WHERE mediatype = 'Blog'
Any advice?
EDIT:
Here is the table with:
There is more columns but these are ones I want to focus on.
Your generate SQL request seems to have a syntax error. Just change the way you generate it.
Instead of
foreach($columns as $val)
$query .= "$val, ";
Try
$query .= implode(', ' $columns);
That will skip the last comma.
The blog column had an extra empty line that 'Blog%' wasn't working on. I went in the database and deleted the extra line and used the query again and it worked.
Thanks everyone for the help :)

PHP - How to order data by ascending or descending

I have a form that allows a user to retrieve information from a database.
Currently users are able to retrieve the information from the database with the code I have provided (probably terrible coding but it works).
Now I would like the data to display in an asc or dsc order depending on what the user selects on the form. But im not too sure how to go about doing that, any help in the right direction would be much appreciated!
The PHP that retrieves the information:
$sql = "SELECT RunnerID, EventID, Date, FinishTime, Position, CategoryID, AgeGrade, PB FROM Results";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>RunnerID</th><th>EventID</th><th>Date</th><th>FinishTime</th><th>Position</th><th>CategoryID</th><th>AgeGrade</th><th>PB</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["RunnerID"]. "</td><td>" . $row["EventID"]. " </td><td>" . $row["Date"]. " </td><td>" . $row["FinishTime"]. " </td><td>" . $row["Position"]. " </td><td>" . $row["CategoryID"]. " </td><td>" . $row["AgeGrade"]. " </td><td>" . $row["PB"]. " </td></tr>";
}
echo "</table>";
}
else {
echo "Error";
}
Rather than having PHP do the work, it would be more standard to modify your SQL query to include ORDER BY xxxx ASC or ORDER BY xxxx DESC. If you have a form which you want to allow them to sort by, a decent alternative might be something like:
$userSelectedProperty = $_GET['ThePropertyIWantToSortOn'];
$userSelectedDirection = $_GET['TheDirectionIWantToSortBy'];
$sql = "SELECT RunnerID, EventID ... FROM Results ORDER BY "; // Note the extra space
switch ($userSelectedProperty)
{
case 'name': { $sql .= "RunnerName"; break; }
case 'age': { $sql .= "AgeGrade"; break; }
...
default: { $sql .= "RunnerID"; break; } // By default, let's sort by ID
}
if ($userSelectedDirection == 'desc')
{
$sql .= " DESC"; // Note the preceding space.
}
else
{
$sql .= " ASC"; // Note the preceding space.
}
This way, the sorting is already done on the database, so you're retrieving the data back in the order you want it already. The reason that I'm using switch statements and if statements even when it looks like it's the same data is that it avoids a vulnerability known as SQL injection. Basically, if you just directly use the variable to build the SQL query, there's nothing stopping some malicious user from providing code that lets them modify the query's intention. For instance, if they passed in something like MyName; DELETE FROM Results; as the value for the form input used to generate the field $userSelectedProperty, the resulting $sql string would be something like SELECT RunnerID ... FROM Results ORDER BY MyName; DELETE FROM Results;. Well, that's really bad because to SQL, it's two valid statements. This isn't the best or most comprehensive definition if this is your first time hearing about it, but if you're curious about how to avoid it, I would suggest looking into SQL injection guides.
$fields = array( "RunnerID", "EventID", "Date", "FinishTime", "Position", "CategoryID" );
$orderby = 0;
$asc = 0;
if( isset($_GET['orderby'])) $orderby = (int)$_GET['orderby'];
if( isset($_GET['asc'])) $asc = (int)$_GET['asc'];
$sql = "SELECT RunnerID, EventID, Date, FinishTime, Position, CategoryID, AgeGrade, PB FROM Results";
$sql .= " ORDER BY " . $fields[$orderby];
$sql .= " " . $asc ? "ASC" : "DESC";
Rather than having the server do the work, consider having the browser do it instead. Offloading work to the browser is an extremely useful skill, especially with very busy websites.
Put the data into a table without regard for sort order. Then use JavaScript to implement sorting. There are plenty of ways of doing this, for instance:
var tbl = document.getElementById('mytable'),
trs = tbl.rows, l = trs.length, i, tmp = [];
for( i=0; i<l; i++) tmp.push(trs[i]);
tmp.sort(function(a,b) {
// compare the rows how you want.
// return -1 if a comes before b
// return 1 if b comes before a
// return 0 if they are equal
});
for( i=0; i<l; i++) tbl.appendChild(tmp[i]);
You can also look into one of the many plug-ins out there on the internet to do this, such as Footable.
Of course, you can always support non-JS users (how outdated are they?) with:
<noscript>Sort ascending</noscript>
When that parameter is present, do the sorting server-side for them, as per the other answers. The overwhelming majority of the time, though, it will be done with JavaScript.

PHP: display items from array to string NOT working

I'm having an issue with converting an array to individual strings and outputting the strings. I'm trying to store each converted string into it's own variable and output each variable to the string using an echo statement. I have already set up a mysqli connection. $connection is the mysqli connection. I've already tried using serialize() and implode() functions. There are four database colums (id, name, email, phonenumber). I commented out some code so you can see what I've been trying. I still can't seem to figure it out. I've included my code below. Thanks.
function get_random_info($connection)
{
$temp = mysqli_query($connection,"SELECT RAND() * FROM distributors LIMIT 1");
$info = $temp;
return $info;
}
//$random_distributor = serialize(get_random_info($con));
//$random_distributor = implode(get_random_info($con));
$random_distributor = $info;
//TEST WITH print_r
print_r ($random_distributor);
//$random_id = $random_distributor[0];
//$random_name = $random_distributor[1];
//$random_email = $random_distributor[2];
//$random_phonenumber = $random_distributor[3];
// TEST OUT INFORMATION. DISPLAY TO SCREEN.
echo "Random name is" . $random_name. "His id in the database is" . $random_id . ".
His email address is {$random_email} and his phone number is {$random_phonenumber}";
these are all commented out so it couldn't possibly work.
//$random_id = $random_distributor[0];
//$random_name = $random_distributor[1];
//$random_email = $random_distributor[2];
//$random_phonenumber = $random_distributor[3];
and you have a function that you never call
get_random_info
I figured it out with some help from you guys. Thanks for pointing me in the right direction. Below is the solution.
<?php
function get_random_info($con)
{
$random_distributor = mysqli_query($con, "SELECT * FROM distributors ORDER BY RAND() LIMIT 1");
return $random_distributor;
}
$row = mysqli_fetch_array(get_random_info($con),MYSQLI_ASSOC);
// TEST OUT INFORMATION. DISPLAY TO SCREEN.
echo "Random name is ". $row["name"] . ". His id in the database is ". $row["id"]. ". His email address is ". $row["email"]. " and his phone number is ". $row["phonenumber"];
mysqli_close($con);
?>

Separate merged SQL rows with a comma

I'm having a bit of trouble getting my retrieved values from an SQL query into the correct format.
I've managed to join multiple rows into the one value, however I am not sure how to make it separate each of the values with a comma. Essentially I need all the ID's of a product to be retrieved as, for example, if the database had values of '5,6,9,1' '1,3,4' and '2,1' I want it to throw a comma in between each like -> '5,6,9,1,1,3,4,2,1' instead is doing something more like -> '5,6,911,3,42,1' which is what it is doing at the moment.
The code I'm using is below. Any help would be greatly appreciated.
$hist = "SELECT ORDITEMS FROM cust_orderc WHERE ORDDATE >
to_date('".$olddate."','dd/mm/yyyy')";
$histitem = OCIParse($db, $hist);
OCIExecute($histitem);
while($row = oci_fetch_array($histitem)){
$pastitem .= $row['ORDITEMS'];
}
echo "$pastitem";
You can do same in oracle using LISTAGG
$hist = "SELECT LISTAGG(ORDITEMS) as ORDITEMS FROM cust_orderc WHERE ORDDATE > to_date('".$olddate."','dd/mm/yyyy')";
Edit OR PHP way
$pastitem = '';
while($row = oci_fetch_array($histitem)){
$pastitem .= $row['ORDITEMS'] . ',';
}
$pastitem = trim($pastitem, ",");
echo $pastitem;

Categories