Replace string at particular position in function In PHP? - php

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>

Related

PHP+MySQL Printing query results

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%'");
}

Duplicating result due to loop

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";
}
?>

Displaying Moodle database data as ul li using php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Nested array. Third level is disappearing
I kinda have a problem here with displaying moodle database data as ul li form using php.
I want to display all the categories of courses, not courses, in their proper nested form as ul li.
The table I'm working on is mdl_course_categories.
Whenever the php script runs, the list must be updated dynamically
The code looks as shown:
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("moodle19", $con);
$result = mysql_query("SELECT name AS COURSE_NAME,parent FROM mdl_course_categories");
if (isset($result)!=1) {
$message = 'Invalid query: ' . mysql_error() . "\n";
}
echo "<p> The courses taught are: </p>";
while ($row = mysql_fetch_array($result)) {
$b=$row['COURSE_NAME'];
$c=$row['parent'];
// $a=mysql_query("Select id from mdl_course_categories");
// $condition=mysql_query("SELECT name AS COURSE_NAME FROM mdl_course_categories WHERE parent='0'");
if ($c==0) {
echo "<ul>
<li>" .$b. "</li>
</ul>";
}
else {
echo "<ul>
<li>" .$b. "</li>
</ul>";
$result1 = mysql_query("SELECT name AS COURSE_NAME FROM mdl_course_categories WHERE depth!='1'");
while ($row1 = mysql_fetch_array($result1)) {
$b1=$row1['COURSE_NAME'];
echo "<ul>
<li>" .$b1. "</li>
</ul>";
}
}
}
?>
I have confusion in understand what is going wrong?
I think this will helpful for you -
$query_catetories = mysql_query('SELECT cc.id, cc.parent, cc.name FROM mdl_course_categories cc ');
$categories = mysql_fetch_all($query_catetories);
$tmp_categories = array();
foreach ($categories AS $row) {
$row['id'] = (int) $row['id'];
$row['parent'] = (int) $row['parent'];
if (!$tmp_categories[$row['parent']])
$tmp_categories[$row['parent']] = array();
$tmp_categories[$row['parent']][] = $row;
}
$course_catetories = buildNode($tmp_categories);
echo '<ul>';
foreach ($course_catetories as $course_catetory) {
print_category_child($course_catetory);
}
echo '</ul>';
function print_category_child($category) {
echo '<li>' . $category['name'];
if (array_key_exists('children', $category)) {
echo '<ul>';
foreach ($category['children'] as $child) {
print_category_child($child);
}
echo '</ul>';
}
echo '</li>';
}
function buildNode($inputArray, $parent = 0) {
$return = array();
foreach ($inputArray[$parent] AS $key => $row) {
if (#$inputArray[$row['id']]) {
$row['children'] = buildNode($inputArray, $row['id']);
}
$return[] = $row;
}
return $return;
}
function mysql_fetch_all($result) {
$all = array();
while ($all[] = mysql_fetch_assoc($result)) {
}
return array_filter($all);
}
Thanks

Error when using mysql_fetch_array();

table data(id, name)
function getData() {
$data = array();
$sql = 'Select * From data';
$query = mysql_query($sql);
if(!$query) {
echo "Error: " . mysql_error();
exit;
}
while($row = mysql_fetch_array($query)) {
$data[] = $row;
}
return $data;
}
$data = $this->getData();
foreach($data as $dt) {
echo $dt->name;
}
I get an error when I echo $dt->name;, the output is null, How do I fix it ?
$dt is not an object but a array. $dt->name should be $dt['name'].
Try:
var_dump($data);
//if its not a class then simply do
$data = getData();

PHP Query + IF ELSE

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>";
}
}
}

Categories