Combine Multiple rows from mysql array - php

right guys im having trouble with one.
what i want to do is have a variable which is made from a mysql query. the problem i have is that it needs to contain multiple rows from the query and combine them into one.
currently i have
$lender = mysql_query("Select * from lender where reference = '$reference'");
while($lenderrow=mysql_fetch_array($lender)) {
$lender1 = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" . $lenderrow["amount"]
echo '<br />';
}
so basically i want it to take this format if it has multiple rows
blackhorse htfhg125h £250
santander htdhfr58hryf £541
Test 125452asaed2 £760
currently i only get the last result when i echo $lender 1 (obviously because its the last call in the while loop)
Cheers In Advance

You need to use a other array.
<?php
$lender = mysql_query("Select * from lender where reference = '$reference'");
$formated_lender = array();
while ($lenderrow=mysql_fetch_array($lender)) {
$formated_lender = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" .
$lenderrow["amount"];
}
foreach ($formated_lender as $row)
{
echo $row . '<br />';
}
Or, if you would just one variable containing all the row, replace $lende1 = ... by $lender1 .= ...

Just put your echo inside the loop. A loop isn't restricted to one statement.
$lender = mysql_query("Select * from lender where reference = '$reference'");
while($lenderrow = mysql_fetch_array($lender)) {
$result = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" . $lenderrow["amount"];
echo $result . "<br />";
}
If you want it in an array, you can use an empty while loop too:
$lender = mysql_query("Select * from lender where reference = '$reference'");
$results = array();
while($results[] = mysql_fetch_array($lender)); // Empty loop
Also, you might want to be careful about SQL injection if $reference is user-supplied and unescaped.

Related

Finding pattern according to variable content

I would like to do something quite simple but I dont know the right code in php.
I have a variable $go which content is GO:xxxxx
I would like to query that if the content of a variable has the pattern "GO:" and something else, echo something, but if not, echo another thing
I want to declare an if statement like:
if (preg_match('/GO/', $go) {
echo "something";
}
else {
echo "another thing";
But I cannot make it work...
I want to embed this statement between this portion of my script:
$result = mysqli_query($enlace,"select count(distinct name2) as total from " . $table . " where go_id like '%" . $go . "%'");
$items = mysqli_fetch_assoc($result);
echo "<br/>";
echo "<b> The total number of genes according to GO code is:</b> " . $items['total'];
mysqli_free_result($result);
$result2 = mysqli_query($enlace,"select count(distinct name2) as total from " . $table . " where db_object_name like '%" . $go . "%'");
$items2 = mysqli_fetch_assoc($result2);
echo "<br/>";
echo "<b>The total number of genes according to GO association is:</b> " . $items2['total'];
mysqli_free_result($result2);
As it is right now, the variable $go can have a value like GO:xxxx or a random sentence, and, with this code, I get two strings, one with value 0 and another with value according to the total apperances matching $go content.
What I want is to declare an if statement so that it just prints one string, the one that has the number of matches according to $go content, but not both.
Any help?
Use strpos():
if (strpos($go, 'GO:') !== false) {
echo 'true';
}
Try this
echo (!strpos($go, 'GO:')) ? "another thing" : "something";
Will surely work

While statement only echoing last result

I am very new, I am having a small problem.. I cannot get my while loop to loop through my entire result set, it is only retrieving the last result set, and i am expecting 2 result sets.
I echo'd my query out to see the result i would get, and the echo printed out both the result sets i want to print out. Leading me to the confusion my while loop is the issue.
I have looked through lost on here but the posts i have seen it was a problem with their query, rather then their while loop. Any assistance would be greatly appreciated. I have used different posts on here to construct my query, but i don't know where to go from here.
date_default_timezone_set("Europe/London");
$date = jddayofweek(unixtojd());
$sql = "SELECT * FROM tbl WHERE ID = $ID AND Day = $date";
$results = $conn->query($sql);
echo $sql;
if ($results->num_rows > 0) {
while ($row = $results->fetch_assoc()) {
$output = "Test2" . "</br>" . $row["time"] . "</br>";
}
} else {
$output = $output . "test1" . "</br>";
}
}
You are not echoing anything inside your while loop.
I think you need to concatenate the variable $output.
while ($row = $results->fetch_assoc()) {
$output .= "Test2" . "</br>" . $row["time"] . "</br>";
}
You are overwritting the content of $output on every iteration of the loop, you should use the concatenation operator to attach the value of the content to the end of the string.
$output .= "Test2" . "</br>" . $row["time"] . "</br>";

How to randomize the columns in a selected row in PHP

The selected id will select the row and randomize. However, it could randomize the same elements.
For example:
'I like to play the piano.'
The output I'm expecting is randomized to eg. ' Play the like to I piano '
But what I receives sometimes turns out to be ' I piano piano like to piano'
This words comes from the database(phpmyadmin). How do I make it such that the data will all appear but not repeat?
$strSQL = "SELECT * FROM sentences WHERE id
ORDER BY RAND() LIMIT 1;";
$x = rand(1,4);
echo "$x";
$y = rand(1,4);
echo "$y";
$z = rand(1,4);
echo "$z";
$c = rand(1,4);
echo "$c";
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
echo "<dt>Sentence:</dt><dd>" . $row["$x"] . " " . $row["$y"] . " " . $row["$z"] . " " . $row["$c"] ."</dd>";
}
You can do:
//create an array with numbers 1-4
$order = array(1,2,3,4);
//shuffle them in random order
shuffle($order);
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
//Display all the array values from 0-3 (array index starts from 0)
echo "<dt>Sentence:</dt><dd>" . $row[$order[0]] . " " . $row[$order[1]] . " " . $row[$order[2]] . " " . $row[$order[3]] ."</dd>";
}
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Try using the shuffle() function.
$strSQL = "SELECT * FROM sentences WHERE id
ORDER BY RAND() LIMIT 1;";
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
shuffle($row);
// Write the data of the person
echo "<dt>Sentence:</dt><dd>" . implode(' ', $row) . "</dd>";
}
Unrelated: mysql_* are deprecated as of php 5.5 and will be removed in the future. Use mysqli or PDO instead.

I can't display everything from my table, it only displays the last record

Hey Guys I'm having a hard time printing everything from my table in mysql.
It only prints the last record of the table. Thank you in advance.
Here's my syntax:
//query
$search_query="SELECT offer_no,day,time from offer where subject_id = '" .$search_subject_id ."';";
//execution of query
$result = mysql_query($search_query,$dbhandle);
//fetching result
while ($row = mysql_fetch_array($result)) {
$results =$row['offer_no'] . " " .$row['day']. " " .$row['time'];
}
Output:
1001 MWF 7:00-8:00
Expected Output:
1001 MWF 7:00-8:00, 1002 MWF 8:00-9:00
You need to use either concatenation or array because $results will be reset on each loop and finally takes the last result:
Array:
$results[] =$row['offer_no'] . " " .$row['day']. " " .$row['time'];
Or:
$results .=$row['offer_no'] . " " .$row['day']. " " .$row['time'];
Please note: mysql_* function were deprecated, you can switch to mysqli and PDO and use parametrized query to prevent SQL Injection Attack.
Try this
while ($row = mysql_fetch_array($result)) {
$results[] =$row['offer_no'] . " " .$row['day']. " " .$row['time'];
}
$result_string = "";
if(is_array($results))
{
$result_string = implode(",",$results)
}
echo $result_string;
You have to append each row to a variable, currently, you are overriding the value, leaving only the last one. Try this:
//query
$search_query="SELECT offer_no,day,time from offer where subject_id = '" .$search_subject_id ."';";
//execution of query
$result = mysql_query($search_query,$dbhandle);
$output = "";
//fetching result
while ($row = mysql_fetch_array($result)) {
$output .= $row['offer_no'] . " " .$row['day']. " " .$row['time'];
}
echo $output;
Notice the .= this is shorthand for concatenation of strings to variables.
It always assigns new variable try this one
$results =$results.",".$row['offer_no'] . " " .$row['day']. " " .$row['time'];
let me know if it not work.
Try with $results as an array like
while ($row = mysql_fetch_array($result)) {
$results[] = $row['offer_no'] . " " .$row['day']. " " .$row['time'];
}
You are appending the values to an variable eachtime.So it will holds the last element in the array of mysql_fetch_array for the result.But you need to assign them to an array then it will maintain the assignments of those array elements in the form of an array $result.If you print the $results then you will get the deserver output.
You can also append the results to the $results variable on concating the results like
while ($row = mysql_fetch_array($result)) {
$results .= $row['offer_no'] . " " .$row['day']. " " .$row['time'];
}
echo $results;
And try to avoid mysql_* statements due to the entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.
There are two other MySQL extensions that you can better Use: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql.

MySQL rename column from within PHP

I need to rename columns in my MySQL table using PHP.
This is made difficult because the syntax is ALTER TABLE [table] CHANGE COLUMN [oldname] [newname] [definition]. The definition is a required parameter.
Is there a way to grab the definition and simply feed this back into the SQL statement? Some sample code would be fantastic, thanks!
According to http://codingforums.com/showthread.php?t=148936, you may have to parse the results of SHOW CREATE TABLE to get the current definition, then use that in the ALTER statement.
mysql_fetch_field() may be useful also.
You can read information_schema.
SHOW TABLE STATUS [{FROM | IN} db_name] [LIKE 'pattern' | WHERE expr]
Issue SHOW CREATE TABLE, read off the line describing the column that is of interest, identify the column definition and construct your ALTER TABLE statement.
My solution was this:
$table = "tableName";
$createTableSQL = $dbh->Execute('SHOW CREATE TABLE ' . $table);
$createTableSQL = $createTableSQL[0][1];
$mappingTable = "originalToDevMapping";
//get mapping
$sql = "SELECT origField, newField
FROM " . $mappingTable;
$newColumns = $dbh->Execute($sql);
foreach ($newColumns as $newColumn) {
if (strlen($newColumn['newField'])<1) {
echo "***Removing*** " . $newColumn['origField'] . "<br><br>";
$sql = "ALTER TABLE " . $table . " DROP COLUMN " . $newColumn['origField'];
$dbh->Execute($sql);
if (strlen($dbh->errorStr)>1) {
echo "<br>************************<br>";
echo "<br>ERROR:<br>";
echo $dbh->errorStr;
echo "<br>************************<br>";
}
} else {
echo "Renaming " . $newColumn['origField'] . " to " . $newColumn['newField'] . "<br><br>";
$sql = "ALTER TABLE " . $table . " CHANGE COLUMN " . $newColumn['origField'] . " " . $newColumn['newField'];
$fieldPos = strpos($createTableSQL,$newColumn['origField']);
$definitionStart = $fieldPos + strlen($newColumn['origField']) + 2;
$definitionEnd = strpos($createTableSQL,',',$definitionStart) - 1;
$definition = substr($createTableSQL,$definitionStart,$definitionEnd-$definitionStart+1);
//workaround - if enum type, comma is included.
if (strstr($definition,'enum')) {
//look for comma after enum end bracket.
$commaPos = strpos($createTableSQL, ',', strpos($createTableSQL,')',$definitionStart));
$definition = substr($createTableSQL,$definitionStart,$commaPos-$definitionStart);
}
$dbh->Execute($sql . " " . $definition);
if (strlen($dbh->errorStr)>1) {
echo "<br>************************<br>";
echo "ERROR:<br>";
echo $dbh->errorStr;
echo "<br>************************<br>";
}
}
}

Categories