Stored Procedures PHP - php

My Stored Procedure only works on the first iteration. My code:
// Display Event
$result = mysql_query("select ....",$connection_mercury);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$provider = $row['name'];
$details = mysql_query("CALL $my_schema_to_use.getRefId($provider);",$connection);
while($b_row = mysql_fetch_array($details))
{
$details_result = $b_row['age'] . " - " . $b_row['address'];
}
echo "<td>$details_result</td><td>$id</td>
}
Lets say the outer while loop does 2 loops as expected. But the 'CALL' only returns a value on the first loop every time. The $details variable always remains empty for any loop after the first one.

$details_result varible are overwritting with inner loop.
while($b_row = mysql_fetch_array($details))
{
$details_result = $b_row['age'] . " - " . $b_row['address'];
}
Code should be
while($b_row = mysql_fetch_array($details))
{
$details_result[] = $b_row['age'] . " - " . $b_row['address'];
}

Related

using fetch twice in php to get the data

I'm trying to get a data from db, I would to say welcome $row['name'];
then in a loop need to print the items
if I did the below code, I will get all items except the first item, but if I deleted the $row2 with the welcoming name, I will get all items why ?
is there a way to use this $row = $SQL->fetch() for both?
<?php
session_start();
include "connect.php";
$access = isset($_SESSION["userid"]);
if ($access) {
$SQL = $dbh->prepare("SELECT * from items, users where userid = ?");
$SQL->execute([$_SESSION["userid"]]);
$row2 = $SQL->fetch();
echo "Welcome " . $row2['name'] . "<br>";
while ($row = $SQL->fetch()) {
echo $row["itemname"] . "-" . $row["price"] . "-" . $row["itemqty"] . "<br>";
}
}else{
echo "<h1>Not Logged in. Access denied.</h1>";
}
?>
When you run fetch() you are moving forward the pointer in the result set. So your first call to fetch() gets the first row, second gets the second row, etc.
Probably the easiest approach would be to pull all results into an array and then work with that.
<?php
session_start();
include "connect.php";
$access = isset($_SESSION["userid"]);
if ($access) {
$SQL = $dbh->prepare("SELECT * from items, users where userid = ?");
$SQL->execute([$_SESSION["userid"]]);
$data = $SQL->fetchAll();
$row2 = $data[0];
echo "Welcome " . $row2['name'] . "<br>";
foreach ($data as $row) {
echo $row["itemname"] . "-" . $row["price"] . "-" . $row["itemqty"] . "<br>";
}
} else {
echo "<h1>Not Logged in. Access denied.</h1>";
}

PHP array implode keys and values to function

I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed.
$allstore = $_POST['store'];
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = $store;
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
//Stores to be shown
$allstore = ['s_M9' =>0 , 's_M10' =>1];
$query = (createSelect($allstore));
$result = mysql_query($query);
//rest of code...
As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] .
Now According to the function shown, if I create my own keys and values like this
$allstore = ['s_M9' =>0 , 's_M10' =>1];
the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually?
Thank You
Edit :
<?php
echo "<form action='somewhere.php' method='POST'>";
$query = "SELECT * from stores_list ORDER BY short Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}";
}
}
else{
//No Stores Available
echo "No Stores Found !";
}
echo "</td><input type='submit' value='Search'/></form>";
$allstore = [];
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys
}
}
$query = (createSelect($allstore));
$result = mysql_query($query);
And of course you have to take care of your createSelect function to avoid SQL Injections, please read here

Fetching data from database, not getting correct data

I have a database which looks like so -
I am trying to fetch the top 10 entries based on time (entries with top 10 values in time column). I have the following code.
<?php
include_once("connect.php");
$sql = "SELECT * FROM scores order by time desc limit 10";
$query = mysql_query($sql) or die("systemResult=Error");
$counter = mysql_num_rows($query);
if($counter>0)
{
print("systemResult=Success");
$array = mysql_fetch_array($query);
foreach($array as $data)
{
$athleteName = $data["athleteName"];
$email = $data["email"];
$time = $data["time"];
$timeStamp = $data["timeStamp"];
$country = $data["country"];
print "&athleteName=" . $athleteName;
print "&email=" . $email;
print "&time=".$time;
print "&timeStamp=".$timeStamp;
print "&country=".$country;
}
}
else
{
print("systemResult=Error");
}
?>
The output I am getting is
systemResult=Success&athleteName=7&email=7&time=7&timeStamp=7&country=7&athleteName=7&email=7&time=7&timeStamp=7&country=7&athleteName=4&email=4&time=4&timeStamp=4&country=4&athleteName=4&email=4&time=4&timeStamp=4&country=4&athleteName=G&email=G&time=G&timeStamp=G&country=G&athleteName=G&email=G&time=G&timeStamp=G&country=G&athleteName=n&email=n&time=n&timeStamp=n&country=n&athleteName=n&email=n&time=n&timeStamp=n&country=n&athleteName=2&email=2&time=2&timeStamp=2&country=2&athleteName=2&email=2&time=2&timeStamp=2&country=2&athleteName=I&email=I&time=I&timeStamp=I&country=I&athleteName=I&email=I&time=I&timeStamp=I&country=I
As can be seen, the output I am getting is not what is on the table in database. I am getting wierd values. What am I doing wrong?
You don't need to use for each in your case, and if so, just print $data, try to remove foreach loop, and if you want to get all records, then, use while:
while($data = mysql_fetch_array($query))
{
$athleteName = $data["athleteName"];
$email = $data["email"];
$time = $data["time"];
$timeStamp = $data["timeStamp"];
$country = $data["country"];
print "&athleteName=" . $athleteName;
print "&email=" . $email;
print "&time=".$time;
print "&timeStamp=".$timeStamp;
print "&country=".$country;
}
try
while($data = mysql_fetch_array($query)) {
$athleteName = $data["athleteName"];
//...

put comma after values but not for last one

I am just a beginner in php. I used the following code to display the user names fetched from the database.
$select_tl = "SELECT `varTeamleader` FROM `tbl_team` WHERE `intTeamid` = '" . $id . "'";
$select_tl_res = mysql_query($select_tl);
$select_tl_num = mysql_num_rows($select_tl_res);
if ($select_tl_num > 0) {
$fetch_tl = mysql_fetch_array($select_tl_res);
$tl = $fetch_tl['varTeamleader'];
$sep_tl = explode(",", $tl);
foreach ($sep_tl as $key => $value) {
$sel_tlname = "SELECT * FROM `tbl_user` WHERE `intUserid` = '" . $value . "'";
$sel_tlname_res = mysql_query($sel_tlname);
$sel_tlname_num = mysql_num_rows($sel_tlname_res);
if ($sel_tlname_num > 0) {
$fetch_username = mysql_fetch_array($sel_tlname_res);
$user_name = $fetch_username['varName'];
echo $user_name . ", ";
}
}
}
I need to echo the user_name with comma after every value but not after last one. How can i do that?
Add the items to an array and then implode(',', $arr).
After you're done iterating, remove the last comma. That's an easy way of doing it.
$user_name=substr($user_name,0,-2)

Retrieving values from MySQL

I have a very simple table that contains a list of 'victims' and the corresponding number of that type destroyed. I'm trying to make an output page of this information, using this code:
foreach( $victims as $vic )
{
$hits = mysql_query("SELECT amount
FROM victims
WHERE victim = ".$vic );
echo $hits;
print "$vic: $hits <br /><hr>";
}
However, hits comes out empty. What's wrong with my SQL query?
foreach($victims as $vic)
{
$hits = mysql_query('SELECT amount
FROM victims
WHERE victim = "' . mysql_real_escape_string($vic) . '"');
if($hits && mysql_num_rows($hits)>0) {
while($row = mysql_fetch_array($hits)) {
echo '<p>' . $row['amount'] . ' hits</p>';
}
} else {
echo '<p>' . mysql_error() . '</p>';
}
}
mysql_query() doesn't return the actual result of your query, but rather a resource with which you can then access the results.
This is a typical pattern:
$result = mysql_query(...);
$row = mysql_fetch_assoc($result);
print($row['amount']);
Each call to mysql_fetch_assoc returns the next row of the result set. If you were expecting multiple rows to be returned, you can call this in a while loop:
$result = mysql_query(...);
while ($row = mysql_fetch_assoc($result)) {
print($row['amount']);
}
Since there's no sane error checking in any of the answers, I'll put the whole thing in here:
foreach( $victims as $vic )
{
$sql = "SELECT amount
FROM victims
WHERE victim = '".mysql_real_escape_string($vic)."'";
$result = mysql_query($sql);
$result or die('Query Error: '.mysql_error() . ' - ' . $sql);
$hitsarray = mysql_fetch_assoc($result);
if ($hitsarray) {
$hits = $hitsarray['amount'];
} else {
// No row was found
$hits = 0;
}
echo $hits;
print "$vic: $hits <br /><hr>";
}
Oh, and this fixes the query error that caused the issue in the first place. Note the quotes wrapping the $vic variable in the string, as well as the proper escaping of the string...

Categories