I used to print MySQL query results like this:
$query="SELECT fname,lname,email FROM users";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$i=0;
echo '<table BORDERCOLOR=black>';
?>
<tr>
<th>Vardas</th><th>Pavarde</th><th>E-Mail</th>
</tr>
<?php
while ($i < $num) {
$field1=mysql_result($result,$i,"fname");
$field2=mysql_result($result,$i,"lname");
$field3=mysql_result($result,$i,"email");
echo "<td>";
echo $field1;
echo "</td>";
echo "<td>";
echo $field2;
echo "</td>";
echo "<td>";
echo $field3;
echo "</td>";
echo "</tr>";
$i++;
}
echo "</table>";
But this time I have to use something different , and I was wondering how can I print out my results when using the function/query shown below:
Query code (in 'class DB'):
function query($querytext) {
$rs = mysql_query($querytext, $this->_link);
if($this->_debug) {
$this->addDebugMessage("\t<tr>\n\t\t<td class=\"debug_nr\">".$this->_queryCount++."</td>\n\t\t<td class=\"debug_queInfo\"><b>Query: (".#mysql_num_rows($rs).")</b></td>\n\t\t<td>" . htmlspecialchars($querytext) . "</td>\n\t</tr>\n");
if(mysql_error() != '') {
$this->addDebugMessage("\t<tr>\n\t\t<td class=\"debug_nr\">".$this->_queryCount++."</td>\n\t\t<td class=\"debug_queInfo\"><b>Error #".mysql_errno($this->_link)." :</b></td>\n\t\t<td>" . htmlspecialchars(mysql_error($this->_link)) . "</td>\n\t</tr>\n");
}
}
if($rs) {
$num_rows = #mysql_num_rows($rs);
if($num_rows) {
if($num_rows > 0) {
$rsarray = array();
while($line = mysql_fetch_array($rs , MYSQL_ASSOC)) {
array_push($rsarray, $line);
}
mysql_free_result($rs);
return $rsarray;
} else {
return false;
}
} else {
if(mysql_affected_rows($this->_link) > 0) {
return true;
} else {
return false;
}
}
} else {
return false;
}
}
(in 'class User')
function findUser($phrase){
global $DB;
$results=$DB->query("SELECT * FROM users WHERE fname LIKE '%'$phrase'%' OR lname LIKE '%'$phrase'%' OR email LIKE '%'$phrase'%'");
return $results;
}
In index.php (what do I use to print this out?):
$USER->findUser("john");
or maybe it should be
$results= $USER->findUser("john);
OR
$results=DB->findUser("john");
Seems you have a typo
function findUser($phrase){
global $DB;
$DB->query("SELECT * FROM users WHERE fname LIKE '%'$phrase'%' OR lname LIKE '%'$phrase'%' OR email LIKE '%'$phrase'%'");
}
There is extra quotes in your query.
function findUser($phrase){
global $DB;
$DB->query("SELECT * FROM users WHERE fname LIKE '%$phrase%' OR lname LIKE '%$phrase%' OR email LIKE '%$phrase%'");
}
Related
Ok so I'm trying to make a localhost site that has the same base functions as Phpmyadmin, and everything is working other than displaying a table's data.
here's an example of what I'm trying to accomplish:
though I'm not sure how to accomplish this. Here is some code to show you what I have now
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$columquery = "SHOW COLUMNS FROM " . $table;
$columresult = mysql_query($columquery);
while ($row3 = mysql_fetch_array($columresult)) {
echo "<th>" . $row3['Field'] . "</th>";
}
?>
<?php
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($result2)) {
foreach($row2 as $var) {
echo "<tr><td>" . $var . "</td></tr>";
}
}
?>
</table>
</div>
Yes yes, I know it's horrible.
The other answers use the mysqli API while you're using the older, no longer supported mysql API. I really recommend upgrading to either mysqli or PDO, but if you want to stay with mysql you can use the following solution:
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$shouldOutputHeaders = true;
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_assoc($result2)) {
if ($shouldOutputHeaders) {
echo "<tr>";
foreach (array_keys($row2) as $header) {
echo "<th>" . $header . "</th>";
}
echo "</tr>";
$shouldOutputHeaders = false;
}
echo "<tr>";
foreach ($row2 as $var) {
echo "<td>" . $var . "</td>";
}
echo "</tr>";
}
?>
</table>
</div>
If i understood you well, You need mysqli_fetch_row.
$q= "SELECT * FROM table";
$result = $mysqli->query($q)
while ($row = $result->fetch_row()) {
print ("$row[0], $row[1]);
}
I think you are looking for something very ugly like the following. I found it in the garbage. I am not responsable for any use of it:
<?php
$db=Db::getConnection(); // singleton
$this->var['result']=$db->query($_POST['query']);
if (isset($this->var['result'])) {
echo '<table cellpadding="5" cellspacing="2" border="1"><tbody>';
$titles=array_keys(#$this->var['result'][0]);
echo '<tr>';
foreach($titles as $title)
echo '<th>'.$title.'</th>';
echo '</tr>';
foreach($this->var['result'] as $row) {
echo '<tr>';
foreach($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
}
?>
Db is an standard singleton that contains a mysqli private object.
query() contains something like
$sql = $this->mysqli->query($query);
$this->lastInsertId = $this->mysqli->insert_id;
$errno = $this->mysqli->connect_errno;
if ($errno === 0) {
if ($this->mysqli->field_count > 0) {
while ($row = $sql->fetch_assoc()) $response[] = $row;
return $response;
}else{
return true;
}
}
to create the "array of arrays" response. Suitable for the output you are looking for.
I've added some escaping and only queried the database when needed:
// Print table tags
echo "<table>";
// Print out records
$q = mysql_query("SELECT * FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print out columns
$columns = array_keys($res[0]);
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$columns).'</th></tr>';
// Print out table data
echo'<tr><td>'.implode('</td><td>', array_map('htmlspecialchars',$res).'</td></tr>';
} else {
// IFF there is no data, print out columns
$q = mysql_query("SHOW COLUMNS FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print columns
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$res).'</th></tr>';
}
}
echo '</table>';
Hope this helps,
My code generates only one result e.g "admin", then generates error. Would you please tell me how can i fix this and show all the result.
while($row = mysqli_fetch_assoc($query)) {
$role = $row['userrole'];
Function RoleFunction($roles){
if ($roles==1) {
echo " Admin";
}
else {
echo " User";
}
}
$test = RoleFunction($role);
echo "<tr>";
echo "<td>".$test."</td>";
echo "</tr>";
}
Result : Admin
Fatal error: Cannot redeclare RoleFunction() (previously declared in E:\xampp\htdocs\meds\delete.php:50) in
E:\xampp\htdocs\meds\delete.php on line 50
Keep your function RoleFunction($roles) outside of loop.
function RoleFunction($roles){
if ($roles == 1) {
return " Admin";
}
else {
return " User";
}
}
while ($row = mysqli_fetch_assoc($query)) {
$role = $row['userrole'];
// Print the role
echo "<tr><td>".RoleFunction($role)."</td></tr>";
}
Try the above code. It should be working.
I thin this will work...
Function RoleFunction($roles){
while($row = mysqli_fetch_assoc($query)) {
$role = $row['userrole'];
if ($roles==1) {
echo " Admin";
}
else {
echo " User";
}
$test = RoleFunction($role);
echo "<tr>";
echo "<td>".$test."</td>";
echo "</tr>";
}
}
your function is in loop, it should be outside loop like this:
function RoleFunction($roles){
if ($roles == 1) {
return "Admin";
} else {
return "User";
}
}
while ($row = mysqli_fetch_assoc($query)) {
$role = $row['userrole'];
// Print the role
echo "<tr><td>".RoleFunction($role)."</td></tr>";
}
It will work for sure
I want to Print some dynamically data from my function to passing string in function like this.
My Function
function mysql_funX_Repeter($query,$itemtemplet)
{
$this->mysql_funX_connect();
$result = mysql_query($query) or die("Repeter Query Error.");
if (!$result)
{
$message = 'ERROR:' . mysql_error();
return $message;
}
else
{
$newtempelt = str_replace("Eval", '$row', $itemtemplet);
while ($row = mysql_fetch_array($result))
{
echo $newtempelt;
}
}
}
Passing Value In Function
<ul>
<?php
$rptvalue="<li><a href=''>Eval['name']</a></li>";
$myFun->mysql_funX_Repeter("Select name from tbldemo",$rptvalue);
?>
</ul>
My Output
$row['name']
$row['name']
$row['name']
I want Output
raj
ram
prince
But it's Show me only variable but not show it's database value.
How to solve this...!!!
I would change a little bit your method.
function mysql_funX_Repeter($query,$itemtemplet)
{
$this->mysql_funX_connect();
$result = mysql_query($query) or die("Repeter Query Error.");
if (!$result)
{
$message = 'ERROR:' . mysql_error();
return $message;
}
else
{
while ($row = mysql_fetch_array($result))
{
echo "<li><a href=''>".$row[$itemtemplet]."</a></li>";
}
}
}
And of course, your method invokation:
<ul>
<?php
$rptvalue="name";
$myFun->mysql_funX_Repeter("Select ".$rptvalue." from tbldemo",$rptvalue);
?>
</ul>
And that's how I'd do it to avoid nasty evals. :)
function mysql_funX_Repeter($query,$itemtemplet)
{
$html='';
$this->mysql_funX_connect();
$result = mysql_query($query) or die("Repeter Query Error.");
$num_rows=mysql_num_rows($result);
if($num_rows){
while ($row = mysql_fetch_array($result))
{
$newtempelt = str_replace("Eval", $row['column_name'], $itemtemplet);
$html.="<li><a href=''>".$newtempelt."</a></li>";
}
}
return $html;
}
//calling method mysql_funX_Repeter
<ul>
<?php
$rptvalue="name";
echo $myFun->mysql_funX_Repeter("Select ".$rptvalue." from tbldemo",$rptvalue);
?>
</ul>
Developer My Problem Was Solved.
Thanks for Reply.
My Function
//This Repeter Function Created By Priyank Patel
function mysql_funX_Repeter($query,$itemtemplet)
{
$this->mysql_funX_connect();
$result = mysql_query($query) or die("Repeter Query Error.");
if (!$result)
{
$message = 'ERROR:' . mysql_error();
return $message;
}
else
{
preg_match_all('/{([^}]*)}/', $itemtemplet, $matches);
$select = '';
while($row = mysql_fetch_assoc($result)){
$aux = $itemtemplet;
for($i = 0; $i < count($matches[0]); $i++){
$aux = str_replace($matches[0][$i], $row[$matches[1][$i]],$aux);
}
$select .= $aux."\n";
}
mysql_close();
return $select;
}
}
Calling Style
<ul><?php $templet="<li>{name}</li>";echo $myFun->mysql_funX_Repeter("Select * from tbldemo",$templet);?></ul>
So my code get a value from previous page, compare it with a table field in the database and display success or failure. Here is the original code:
<?php
if ($_GET['q'] !='')
{
include('config.inc');
$foo = $_GET['q'];
$query= "INSERT INTO register(name) VALUES('$foo')";
$result = mysql_query("SELECT * FROM user_student");
while($row = mysql_fetch_array($result))
{
$id= $row['sid'];
if($id==$foo)
{
$res = mysql_query($query);
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
}
else echo "Invalid Command";
?>
Am having duplicating result e.g Student 1124 does not exist!! 10times. I've modify the code to:
while($row = mysql_fetch_array($result))
{
$id= $row['sid'];
if($id==$foo)
{
$res = mysql_query($query);
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
So i've placed the $res outside the loop to avoid duplication result but now it says: variable cannot be resolved Any suggestions?
A bit of changed version of CaldasGSM:
<?php
if (!empty($_GET['q']))
{
include('config.inc');
$foo = mysql_real_escape_string($_GET['q']);
$result = mysql_query("SELECT * FROM user_student WHERE sid = '{$foo}'");
$num_rows = mysql_num_rows($result);
if($num_rows > 0)
{
$res = mysql_query("INSERT INTO register(name) VALUES('$foo')");
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
else
{
echo "Invalid Command";
}
?>
maybe something like
<?php
if ($_GET['q'] !='')
{
include('config.inc');
$foo = $_GET['q'];
$result = mysql_query("SELECT * FROM user_student");
$bRecordExists = false;
while($row = mysql_fetch_array($result))
{
$id= $row['sid'];
if($id==$foo)
{
$bRecordExists = true;
break;
}
}
if($bRecordExists)
{
$res = mysql_query("INSERT INTO register(name) VALUES('$foo')");
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
else
{
echo "Invalid Command";
}
?>
I Have a PHP file doing a query
function getFiles()
{
$solnid = $_GET[id];
$query = mysql_query("SELECT * FROM library WHERE libr_solutionId = '$solnid' AND libr_deleted IS NULL") or die(mysql_error());
$result = mysql_query($query);
if (mysql_num_rows($result)==0) {
echo "<br>No Related Links";
} else {
while($library = mysql_fetch_assoc($query)) {
echo "<span style=\"margin-bottom: 5px;\"><img src=\"images/icon-download-02.png\" align=\"absmiddle\" style=\"margin-right: 5px;\"><span>".$library[libr_c_title]."</span></span><br>";
echo "<br>";
}
}
}
I have tested the query in PHPMyAdmin and I get a result however when running the function in my page it only displays the 'No Related Links' statement any ideas anyone?
Here's the fixed code. :) The problem was that you used mysql_query on a Resource (the first mysql_query), and that will give 0 rows, or an exception..
function getFiles()
{
$solnid = $_GET['id'];
$result = mysql_query("SELECT * FROM library WHERE libr_solutionId = '$solnid' AND libr_deleted IS NULL") or die(mysql_error());
if (mysql_num_rows($result)==0) {
echo "<br>No Related Links";
} else {
while($library = mysql_fetch_assoc($result)) {
echo "<span style=\"margin-bottom: 5px;\"><img src=\"images/icon-download-02.png\" align=\"absmiddle\" style=\"margin-right: 5px;\"><span>".$library['libr_c_title']."</span></span><br>";
echo "<br>";
}
}
}
change your function to (change to lines)
function getFiles()
{
$solnid = $_GET[id];
$result = mysql_query("SELECT * FROM library WHERE libr_solutionId = '$solnid' AND libr_deleted IS NULL") or die(mysql_error());
if (mysql_num_rows($result)==0) {
echo "<br>No Related Links";
} else {
while($library = mysql_fetch_assoc($query)) {
echo "<span style=\"margin-bottom: 5px;\"><img src=\"images/icon-download-02.png\" align=\"absmiddle\" style=\"margin-right: 5px;\"><span>".$library[libr_c_title]."</span></span><br>";
echo "<br>";
}
}
}