How to loop the $row = mysql_fetch_array($rs); - php

I have a table
Now.i have a function in my JS
function add()
{
<?php
include('conn.php');
$rs = mysql_query("select * from position");
$row = mysql_fetch_array($rs);
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo "add2()";
?>}
function add2(){
AddAddress("<?php echo $ss;?>","<?php echo $sss;?>/<?php echo $ssss;?><br /><?php echo $sssss;?>/<?php echo $ssssss;?>");
}
How to get the every date from my table?

Something like this?
function add() {
<?php
include('conn.php');
$rs = mysql_query("select * from position");
while ( $row = mysql_fetch_array($rs) ) {
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo 'AddAddress("' . $ss . '","' . $sss . '/' . $ssss . '<br />' . $sssss . '/' . $ssssss . '");';
}
?>
}
Didn't text the echo 'AddAddress....' line so I hop eI got all the single and double quotes in the right place??

Performing POST requests using Ajax here is an example of sending data from js to php.
also stop naming your vars s,ss,sss,ssss you will have no idea what they mean when you read your code tomorrow..
and try not to use mysql_* functions they have been deprecated switch to mysqli or pdo

I got what would you like to do. In your PHP file:
function add(){
<?php
include('conn.php');
$rs = mysql_query("select * from position");
echo "var data = [] ; "
while($row = mysql_fetch_assoc($rs)){
echo "
data.push({
name: '{$row['Name']}',
nowb: '{$row['nowb']}',
totalb: '{$row['totalb']}',
nowc: '{$row['nowc']}',
totalc: '{$row['totalc']}'
}); \n\r " ;
}
?>
add2(data);
}
function add2(data){
for (var i in data){
var row = data[i] ;
AddAddress(row.name, row.nowb, row.totalb, row.nowc, row.totalc);
}
}

If I understand the question correctly you want to know how to loop through an array in php.
$row = mysql_fetch_array($rs);
foreach($row as $value){
//Do something
}
Read up on it in the docs
http://php.net/manual/en/control-structures.foreach.php

Related

MySQL PHP use query result more that once in HTML

I have an query that shows data from db. I use while loop to display data. Problem is that I can call (echo) result only once.
Here is my code:
$ime_ = "SELECT * FROM `users` WHERE '" . ($_COOKIE['username']) . "' = user_username";
$ime_result = $mysqli->query($ime_);
and later in my html I use this result as:
<?php
if ($ime_result->num_rows > 0)
while($row = $ime_result->fetch_assoc()) {
echo "<h2>" . $row["Ime"] . "</h2>";
}
?>
This work ok, but I want to use this result to display many times in my html. And when copy while loop again later in html no result is given.
Store the string with data from while() into a variable, than apply echo to that variable as many times as you like..
$re_out ='';
if($ime_result->num_rows > 0){
while($row = $ime_result->fetch_assoc()) {
$re_out .="<h2>". $row["Ime"] ."</h2>";
}
}
echo $re_out;
//etc..
echo $re_out;
<?php
if ($ime_result->num_rows > 0)
$ime_result->data_seek(0); // seek to row no. 1
while($row = $ime_result->fetch_assoc()) {
echo "<h2>" . $row["Ime"] . "</h2>";
}
?>
Haven't run script. Try if it works.

PHP and mysqli to modify CSS

I was experimenting if I could use a mySQL database to store CSS settings. I set up a simple database "colors" with one table "color" that had simple structure tag and color columns. In that, one row is h1 => red.
<?php
//function to dynamically change CSS
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
?>
When I tried to convert to a function, the code does not work at all.
<?php
//function to dynamically change CSS
function getCSS($tag)
{
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
}
getCSS('h1');
?>
Help please?
My guess is that in
$query = mysqli_query($link, $q);
$link goes out of scope and is empty. You should pass it to the function as well.
For the record: using $tag without escaping could be an sql injection attack possibility.
in function, there is no $link, you shoud define it as a global variable.
At the start of your function add a reference to your global DB link:
function getCSS($tag) {
global $link;
...
This should work:
<?php
$link = mysqli_connect('server_host', 'user', 'password', 'database') OR die('Could not connect because: '.mysqli_connect_error());
//function to dynamically change CSS
function getCSS($link, $tag){
$q = 'SELECT * FROM colors WHERE tag = "' . $tag . '"' ;
$r = mysqli_query($link, $q);
if(mysqli_num_rows($r)>0){ // check if there are results
while($row = mysqli_fetch_assoc($r)){
//echo '<pre>';
//print_r($row); // print the result array for debugging
//echo '</pre>';
echo $row['color'] . '<br />';
}
return $row;
} else { // if no result is found
echo 'No such tag';
}
}
// test it:
echo '<br />if tag is h1<br />';
getCSS($link, 'h1');
echo '<br />if tag is h2<br />';
getCSS($link, 'h2');
?>

Cakephp query only displays last value of array

I'm sure I'm doing something wrong here but I can't figure it out. I have tried several ways but no luck.
This is my controller:
$result = mysql_query("SELECT name FROM spa_packages") or die(mysql_error());
$names=array();
while ($row = mysql_fetch_row($result)) $names[]=$row[0];
mysql_free_result($result);
foreach ($names as $asd => $lol) {}
$this->set('anything', $lol);
This is where I display it:
if(!empty($anything)) {
echo " '<option value=" . $anything . '">' . $anything . '</option>';
}
Further to my comment and in more of an answer. You are doing something wrong. There is absolutely no reason to use mysql_ functions at all (they are deprecated) and you shouldn't be using any direct db access in an MVC framework like CakePHP
Your code should be more along the lines of
In your Controllers/SpaPackagesController.php index action:
$spaPacakges = $this->SpaPackage->find('all');
$this->set('spaPackages', $spaPackages):
In your Views/SpaPackages/index.ctp
<?php foreach ($spaPackages as $package): ?>
<!-- some html -->
<?php endforeach;?>
You really need to run through some CakePHP beginner tutorials as your question shows a big misunderstanding in how the framework works
Looks like you are trying to do this:
$result = mysql_query("SELECT name FROM spa_packages") or die(mysql_error());
$names = array();
while ($row = mysql_fetch_assoc($result)) {
$names[] = $row["name"]
}
$this->set('anything', $names);
mysql_free_result($result);
And:
if(!empty($anything)) {
foreach($anything as $name){
echo " '<option value=" . $name . '">' . $name . '</option>';
}
}

Transferring DB data between PHP and Javascript 2D array

I am attempting to get all the data from a MySQL db with PHP, initialise a 2D java array and populate it with the PHP data.
I am having trouble embedding JS in the PHP. I have marked up what is working and what isn't.
As you will see, some of the embedded java works but not all.
Any thoughts?
<body>
<?php
$con = mysql_connect("XXXXXX.COM","guest","password");
mysql_select_db("HHG", $con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{
$result = mysql_query("SELECT * FROM articles", $con);
$numrows = mysql_num_rows($result);
echo "DB connection OK <br/>";
echo "Found ";
echo $numrows;
echo " records <br/><br/>";
} // EVERYTHING WORKS UP TO HERE
?>
<script type="text/javascript">
document.write("THIS IS THE FISRT JS DOING SOMETHING"); // THIS DOES NOTHING
numrows = <?php echo $numrows; ?>; // THIS DOES NOTHING
string [][] hhgdata = new string[numrows][4]; // THIS DOES NOTHING
document.write("Records = " + numrows + "<br/>"); // THIS DOES NOTHING
</script>
<?
$counter = 1;
while ($row = mysql_fetch_assoc($result))
{
echo $row["idimg"]; echo "<br/>"; //THIS WORKS
$hhgtitle = $row["hhgtitle"]; //THIS WORKS
echo $hhgtitle; echo "<br/>"; //THIS WORKS
?>
<script type="text/javascript"> //THIS WORKS
counter = <?php echo $counter; ?>; //THIS WORKS
document.write("counter = " + counter + "<br/><br/>"); //THIS WORKS
hhgtitle = <?php echo $hhgtitle; ?>; // THIS DOES NOTHING
document.write("Title: "); // THIS DOES NOTHING
hhgdata[counter][1]= hhgtitle; // THIS DOES NOTHING
document.write(hhgdata[counter][1]); // THIS DOES NOTHING
</script>
<?
$counter++; // THIS WORKS
}
?>
</body>
You are mixing up Java and JavaScript. For example this is Java syntax, you can't write this within a script tag which should only contain JavaScript:
string [][] hhgdata = new string[numrows][4];
The JavaScript arrays are dynamic, this should be enough:
var hhgdata = [];
When you want to add another array into it, as you seem to be doing later in your code, just do this:
hhgdata[counter] = [];
And then assign to the inner array:
hhgdata[counter][1] = hhgtitle;
You are also creating multiple assigning an unquoted string literal to variable with this (assuming $hhgtitle contains a string):
hhgtitle = <?php echo $hhgtitle; ?>;
It should be something like this:
hhgtitle = <?php echo '"' . $hhgtitle .'"'; ?>;
Finally, while it's not incorrect, your PHP while loop is creating multiple script elements in your HTML.
EDIT
I have made the changes described above as well as in comments, copy-paste exactly and see how it goes:
<body>
<?php
$con = mysql_connect("XXXXXX.COM","guest","password");
mysql_select_db("HHG", $con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{
$result = mysql_query("SELECT * FROM articles", $con);
$numrows = mysql_num_rows($result);
echo "DB connection OK <br/>";
echo "Found ";
echo $numrows;
echo " records <br/><br/>";
} // EVERYTHING WORKS UP TO HERE
?>
<script type="text/javascript">
document.write("THIS IS THE FISRT JS DOING SOMETHING"); // THIS DOES NOTHING
numrows = <?php echo $numrows; ?>; // THIS DOES NOTHING
var hhgdata = new Array(numrows); // THIS DOES NOTHING
document.write("Records = " + numrows + "<br/>"); // THIS DOES NOTHING
</script>
<?php
$counter = 1;
while ($row = mysql_fetch_assoc($result))
{
echo $row["idimg"]; echo "<br/>"; //THIS WORKS
$hhgtitle = $row["hhgtitle"]; //THIS WORKS
echo $hhgtitle; echo "<br/>"; //THIS WORKS
?>
<script type="text/javascript"> //THIS WORKS
var counter = <?php echo $counter; ?>; //THIS WORKS
document.write("counter = " + counter); //THIS WORKS
hhgtitle = <?php echo '"' . $hhgtitle . '"'; ?>; // THIS DOES NOTHING
document.write("Title: "); // THIS DOES NOTHING
hhgdata[counter] = [];
hhgdata[counter][1]= hhgtitle; // THIS DOES NOTHING
document.write("<br />hhgdata[counter][1]: " + hhgdata[counter][1]); // THIS DOES NOTHING
</script>
<?php
$counter++; // THIS WORKS
}
?>
</body>
Why not just take the PHP array of data and json_encode it? Then you can work with it in Javascript, see below:
var json = <?php echo json_encode($foo); ?>;
You can learn more about how to do this here: http://www.openjs.com/scripts/data/json_encode.php

Checking querystring values in PHP

http://localhost/?area=characters&name=Michal+Stroganof
$result = mysql_query("SELECT * from players WHERE name = '$_GET[name]'");
while ($row = mysql_fetch_assoc($result)) {
echo "Name: " .$row['name']. "<br>";
echo "Level: " .$row['level']. "<br>";
}
This is all code of my characters.php
If the get variable "name" is not included in the URL i want to show a search form that searches the table players. How would I do this?
Do you mean just to change your SQL string like so?
$sql = 'SELECT * from players';
if (isset($_GET['name'])) {
$safename = mysql_real_escape_string($_GET['name']);
$sql .= " WHERE name='$safename'";
}
$result = mysql_query($sql);
Be sure to sanitize your SQL!
Use isset():
if (isset($_GET['name'])) {
// your above code
} else {
// display form
}
Quick and dirty:
<?php
if (!isset($_GET['name']))
{
echo '<form action="'. $_SERVER['PHP_SELF'] .'" method="GET">'
.'<input type="text" name="name" />'
.'</form>';
}
else
{
// your current code that queries your database here
}
?>

Categories