Mysql results duplicated even though the query does not match - php

apologize firstly for my questionable coding in php/mysql however this is all self taught (possibly not best practice)
All my code seems to work , however when the results are written to the page any $dxcall that is not in the $qrzdata database gets filled with the last result all other data displays fine. I have tried changing the like $dxcall to = $dxcall. I have also tried combining the fetch arrays too incase my issues was there too. But clearly my code does not know how to handle where there is not data match in the qrzdata database and to move on.
$frqry is the main data, all the other mysql_query's be it the $squares and $qrzdata are matching what comes from $frqry. Hope this makes sense !!
Here is my code
$frqry = mysql_query("select * from spots where freq between '69900' and '70300' ORDER BY datetime desc limit 30");
While ($r0 = mysql_fetch_array($frqry))
{
$freq = $r0["freq"];
$dxcall = $r0["dxcall"];
$datetime = $r0["datetime"];
$comments = $r0["comments"];
$spotter = $r0["spotter"];
$dt = date('d-m-y H:i ', $datetime);
$qra = $r0["loc"];
$squares = mysql_query("select * from squares where callsign like '$dxcall' limit 1");
while ($r1 = mysql_fetch_array($squares))
{
$qra = $r1["loc"];
}
$qrzdata = mysql_query("select * from qrzdata where callsign = '".$dxcall."' limit 1");
While ($r2 = mysql_fetch_array($qrzdata))
{
$country = $r2["country"];
$firstname = $r2["firstname"];
$city = $r2["city"];
}
Any help is greatly appreciated. Thank you.

You need to learn about the power of the JOIN ;)
Your whole code could be rewritten in one single query :
disclaimer: not tested, but you certainly get the idea
SELECT * FROM spots
JOIN squares ON (squares.callsign = spots.dxcall) -- this comes in stead of your first inner loop
JOIN qrzdata ON (qrzdata.callsign = spots.dxcall) -- this is your second loop
WHERE freq BETWEEN 69900 AND 70300 -- remove quotes, you are dealing with integers, not strings (hopefully)

You have to reset your vars!
While ($r0 = mysql_fetch_array($frqry))
{
$qra = '';
$country = '';
$firstname = '';
$city = '';
or you will allways get the last value

Related

Mysql Data Only Pulling Last Result Into Json Array

I'm pulling multiple rows from a table and formatting them to this standard: 3 Swords, 5 Daggers, etc.
Well When I try to put that data into a json Array, It's only pulling the last result as this [{"weapons":"You Used: 3 Rusty Dagger's, "}] Which it should say: [{"weapons":"You Used: 3 Rusty Dagger's, 2 Swords"}]
Here's The Query I'm currently using, Which will show perfectly inside of the while loop:
$get_weapons = mysql_query("SELECT
O.player_id,
O.item_id,
O.name,
O.attack,
O.defense,
O.type,
O.owned,
(SELECT
sum(owned) FROM items_owned
WHERE owned <= O.owned AND player_id=$id) 'RunningTotal'
FROM items_owned O
HAVING RunningTotal <= $mob_avail
ORDER BY attack DESC");
// Get Weapon Info
while($weapon = mysql_fetch_array($get_weapons)){
$weapon_id = $weapon['item_id'];
$weapon_name = $weapon['name'];
$weapon_attack = $weapon['attack'];
$weapon_defense = $weapon['defense'];
$weapon_owned = $weapon['owned'];
// Formatting Weapons Message
$weapon_message = 'You Used: '.$weapon_owned.' '.$weapon_name.'\'s, ';
}
$data[] = array('weapons'=>$weapon_message);
echo json_encode($data);
I understand that the $data array is outside of the while loop, But I'm only needing a total of one arrays, so I'm kind of stuck on what to do to fix this issue. Any help would be awesome
You should add one static variable before append the results into the message.
Here is the reference answer:
$get_weapons = mysql_query("SELECT O.player_id, O.item_id, O.name, O.attack, O.defense, O.type, O.owned, (
SELECT sum(owned) FROM items_owned WHERE owned <= O.owned AND player_id=$id) 'RunningTotal' FROM items_owned O HAVING RunningTotal <= $mob_avail ORDER BY attack DESC");
// Initialize the message
$weapon_message = 'You Used: ';
// Get Weapon Info
while($weapon = mysql_fetch_array($get_weapons)){
$weapon_id = $weapon['item_id'];
$weapon_name = $weapon['name'];
$weapon_attack = $weapon['attack'];
$weapon_defense = $weapon['defense'];
$weapon_owned = $weapon['owned'];
// Formatting Weapons Message
$weapon_message = $weapon_message.$weapon_owned.' '.$weapon_name.'\'s, ';
}
$data[] = array('weapons'=>$weapon_message);
echo json_encode($data);

Between min and max value mysqli

I have to create a PHP web page with two text fields in which the user can enter minimum and maximum item prices from a SQL database. So I have items with prices. For example, if a user wants to see items between the prices 4 and 15, he can submit it and then it will show only the items in that price range. How can I do this? How to echo this?
Thank you!
I have this so far:
$min=$_POST["minimum"];
$max=&$_POST["maximum"];
$result = mysqli_query($con,"SELECT * FROM items WHERE selling price BETWEEN {$min}+1 AND {$max}");
Apart from a major SQL Injection issue, your script is looking fine. Just some small typs and syntax errors. Compare this one to yours:
$min=(int)$_POST["minimum"];
$max=(int)$_POST["maximum"];
$result = mysqli_query($con,"SELECT * FROM items WHERE selling_price BETWEEN {$min}+1 AND {$max}");
So, what did I change?
At least cast posted values to int to remove the chance of anyone injecting malicious SQL code into your query. You should use proper escaping in the future
You dont need to add the & character before in line two. You dont need to assign the value by reference. just assign the plain old way
column and table names can not conain spaces in MySQL. Are you sure that is the correct name of the column? Maybe there was an underscore?
One of the many safer and simpler ways of doing that would be
$dsn = "mysql:dbname=test;host=127.0.0.1";
$dbh = new PDO($dsn, 'username', 'password');
if(isset($_POST["minimum"]) && isset($_POST["maximum"]))
{
$min=floatval($_POST["minimum"]); //+1 is not needed
$max=floatval($_POST["maximum"]);
$sth = $dbh->prepare("SELECT * FROM items WHERE selling_price BETWEEN ? AND ?");
$sth->execute(array($min,$max));
while($row = $sth->fetch(PDO::FETCH_OBJ))
{
print_r($row);
}
}
That should do the trick for you:
if(isset($_POST['minimum'])){
$min = $_POST['minimum'];
}else{
$min = '';
}
if(isset($_POST['maximum'])){
$max = $_POST['maximum'];
}else{
$max = '';
}
$sql = "SELECT * FROM item WHERE selling_brice > '$min' AND selling_price < '$max'";
$query = mysqli_query($con, $sql);
$count = mysqli_num_rows($query);
if($query == true && $count > 0 ){
while ($row = mysqli_fetch_assoc($query)){
$price .= $row['selling_price'];
$price .= '<br />'
}
echo $price;
}else{
echo "NO results to Display";
}
Ofcourse this is not the best programing mysql injections, your query uses * etc....but this should work.

Error printing results from a query that is inside a for loop

I need help on this.
I have to write a query 12 times with just a different value so I did this and it worked fine:
for ($q=1; $q<=11; $q++) {
$ingConcepto[$q] = "SELECT
tbl_ingresos.cantidadpagada AS cp,
tbl_conceingresos.concepto AS concepto,
tbl_ingresos.fechapertenece
FROM
tbl_ingresos
LEFT JOIN
tbl_conceingresos
ON
tbl_ingresos.idtipoingreso = tbl_conceingresos.idingreso
WHERE
MONTH(fechapertenece) = '$q'
AND
YEAR(fechapertenece) = $elcueri1";
$resIC[$q] = mysql_query($ingConcepto[$q],$tewNEW);
$ingConcepto[$q] = mysql_fetch_array($resIC[$q]);
}
The problem comes when I need to print a value it does not display anything:
echo $ingConcepto7['cp'];
Thanks.

Updating a row number which has been randomised

So I currently have a random number being generated in PHP and I want to know how I go about updating the row number in my selected table. Code below:
$sxiq = mysql_query("SELECT * FROM `starting_eleven` WHERE `team_id`=$uid");
$sxir = mysql_fetch_row($sxiq);
$first = rand(1,11);
$stat_changed = rand(11,31);
$up_or_down = rand(1,2);
if ($up_or_down == 1) {
$player_name = explode(" ", $sxir[$first]);
$fn = $player_name[0];
$ln = $player_name[1];
$statq = mysql_query("SELECT * FROM `players` WHERE `first_name`=$fn AND `last_name`=$ln AND `user_id`=".$_SESSION['user_id']);
$statr = mysql_fetch_row($statq);
$stat = $statr[0];
}
I would like to update the row $stat_changed from the database, but I'm not sure if this is possible without doing a long if statement, telling the code if $stat_changed = 13 $stat = pace or something along those lines, but if this is the way it must be done then I'll have to. Just thought I'd see if there was any other simpler ways of doing this.
Thanks in advance
if ($stat_changed == 13) {
//insert UPDATE statement here
}

Separate merged SQL rows with a comma

I'm having a bit of trouble getting my retrieved values from an SQL query into the correct format.
I've managed to join multiple rows into the one value, however I am not sure how to make it separate each of the values with a comma. Essentially I need all the ID's of a product to be retrieved as, for example, if the database had values of '5,6,9,1' '1,3,4' and '2,1' I want it to throw a comma in between each like -> '5,6,9,1,1,3,4,2,1' instead is doing something more like -> '5,6,911,3,42,1' which is what it is doing at the moment.
The code I'm using is below. Any help would be greatly appreciated.
$hist = "SELECT ORDITEMS FROM cust_orderc WHERE ORDDATE >
to_date('".$olddate."','dd/mm/yyyy')";
$histitem = OCIParse($db, $hist);
OCIExecute($histitem);
while($row = oci_fetch_array($histitem)){
$pastitem .= $row['ORDITEMS'];
}
echo "$pastitem";
You can do same in oracle using LISTAGG
$hist = "SELECT LISTAGG(ORDITEMS) as ORDITEMS FROM cust_orderc WHERE ORDDATE > to_date('".$olddate."','dd/mm/yyyy')";
Edit OR PHP way
$pastitem = '';
while($row = oci_fetch_array($histitem)){
$pastitem .= $row['ORDITEMS'] . ',';
}
$pastitem = trim($pastitem, ",");
echo $pastitem;

Categories