As you can see from the code below im very new to PHP, so please excuse the newbie question but ive been struggling with this all afternoon and just cant figure out what exactly is the problem.
Basically Ive got 3 dropdown menus for team1, team2 and venue.
When user selects teams and venue an isset function is triggered and I extract the result from the game out of my database.
As you can see in the code below I use 3 echo statements to test if correct values from dropdown menus has been captured. When I open the page the echo statements confirm the correct results are captured from the drop-downs, I go on and query the database with the variables I echoed above.
The Problem
In the while loop, I want to echo the results from the query BUT nothing gets displayed. I tried doing a var_dump to see the contents of the variables but NOTHING gets displayed. What am I doing wrong?
foreach($_REQUEST["team1"] as $teamone){
$team1 = $teamone;
}
foreach($_REQUEST["team2"] as $teamtwo){
$team2 = $teamtwo;
}
foreach($_REQUEST['venue'] as $venue){
$venue = $venue;
}
//These echo statments are a test to see if the correct dropdown values has been captured
echo $team1.'<br>';
echo $team2.'<br>';
echo $venue;
//Use results from dropdown menu to query database
$result = mysql_query('SELECT *
FROM `results`
WHERE `hometeam` = "$team1" && `awayteam` = "$team2"') or
die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['awayteamscore'];
echo $row['hometeamscore'];
}
If anyone can point me in the right direction it would be greatly appreciated.
I suspect you're receiving sql syntax error for two reasons at least
First when you want to use the variable value within string you must use double embracing quotes
$sql="select * from mytable where col1='$my_var'";
And second: SQL expects string values ebraced with simgle quotes as I pointed above. In your case you use "" quotes.
And one more recommendation. When debugging php app it might be useful to enable extended output by inserting
error_reporing(E_ALL);
somewhere in the beginning of php script
you mixed between double and single quotes . while variables shouldnt be rounded by double quotes.
$result = mysql_query(" SELECT *
FROM `results`
WHERE `hometeam` = '$team1' && `awayteam` = '$team2' ") or
die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['awayteamscore'];
echo $row['hometeamscore'];
}
You put your SQL query in single quotes and variables do not work in there. Try this:
<?php
$var = "stuff";
echo '$var';
echo "$var";
?>
What you can do instead is to concatenate strings like this:
$result = mysql_query('SELECT *
FROM `results`
WHERE `hometeam` = "'.$team1.'" && `awayteam` = "'.$team2.'"')
My Friend Your code is just fine you just need to check that your submiting the dropboxes with the form so first check your html and when you var_dump($_REQUEST) it should be an array containing all the values that you trying to gather
Your foreach loops are overriding the values. It would be best to put it in an array like so
$team1 = array();
foreach($_REQUEST["team1"] as $teamone){
$team1[] = $teamone;
}
if you need to make the values of $team1 into a string then this would be more appropriate
$team1 = "";
foreach($_REQUEST["team1"] as $teamone){
$team1 .= $teamone;
}
Fixing the above first might help. If not then maybe the problem is in your db queries.
//Using double quotes
"SELECT * FROM `results` WHERE `hometeam` = '$team1' && `awayteam` = '$team2'"
//Using single quotes
'SELECT * FROM `results` WHERE `hometeam` = "'.$team1.'" && `awayteam` = "'.$team2.'"'
Then display the result
while($row = mysql_fetch_array($result)){
echo $row['awayteamscore'];
echo $row['hometeamscore'];
}
Related
// This gets all the users that are active
// The limit is completely random, it is set to 2 for this example
$sql = <<<SQL
SELECT *
FROM `accounts`
WHERE active = 1
LIMIT 2
SQL;
if(!$getaccounts = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while ($row = $getaccounts->fetch_assoc()) {
$getid = $row["id"].',';
$getid = substr($getid, 0, -1);
$getusername = $row["username"];
$getpassword = $row["password"];
echo $getid;
echo $getusername."<br>";
echo $getpassword."<br>";
}
I know this hasn't been prepared but I am not using it for anything other than personal use.
I cannot understand why this is not getting rid of the last comma?
The output may be something like "32,14,"
And I want to get rid of the last comma by using the "substr" function.
But the output that that I get from $getid is "3214" (It gets rid of all the commas instead of just the last one.
I need it to output "32,14" but it's not working?
Could someone please tell me where I am going wrong?
If I do rtrim, it does the same thing and gets rid of all the commas! I am going to update something in the database using the ids, and that is why I need to get rid of the last comma
And I know this code is not secure, I am not using it for anything other than personal use and I was hoping someone could help me figure this out, I have been attempting it for days, it seems really simple and I bet I am missing something really stupid!
You have a XY Problem.
You want to concat all the id's into a comma-seperated string.
Here's a much easier solution by adding the items to an array and then implode().
<?php
// rest of your code
$ids = Array();
while ($row = $getaccounts->fetch_assoc()) {
$ids[] = $row["id"];
$getusername = $row["username"];
$getpassword = $row["password"];
echo $getusername."<br>";
echo $getpassword."<br>";
}
echo "ids: " . implode(",",$ids);
You should write code like..
$getid = "";
while ($row = $getaccounts->fetch_assoc()) {
$getid .= $row["id"].',';
}
$getid = rtrim($getid,',');
$q = " UPDATE accounts SET active = '0' WHERE id IN ($getid) ";
I'm using PHP and I do a mysql query and I save the result of this query in an array. Then, I use a loop and into the loop i do another mysql query using the values of the array in the where clause. It's right but if I try to get the result of the query outside the loop I can't.
Here an example code
$result=$mysqli->query("SELECT code FROM referee");
$i=0;
$arcode=array();
while($row=$result->fetch_array()){
$arcode[$i]=$row["code"];
$i++;
}
for($j=0;$j<sizeof($arcode);$j++){
$result2=$mysqli->query("SELECT code, time FROM match where referee_code IN ($arcode[$j])");
}
/*Here I can't get the result values*/
$matcode=array();
$hour=array();
$k=0;
while($row2=$result2->fetch_array()){
$matcode[$k]=$row2["code"];
$hour[$k]=$row2["time"];
}
If I put all in the same loop I get the result repeated (This code is one example of all my code but the idea is the same in the rest).
You are overwriting the result set values into $result2.
The correct method would be something like:
$matcode = array();
$hour = array();
$result2 = $mysqli->query("SELECT code,
time
FROM `match`
WHERE referee_code IN (SELECT code
FROM referee)");
while ($row2 = $result2->fetch_array())
{
$matcode[] = $row2["code"];
$hour[] = $row2["time"];
}
You may change the index values according to the way you want the array to look like.
Also match is a reserved word. So you would have to enclose it in backticks.
If you want to print complete data then try this :
$matcode = array();
$hour = array();
$result2 = $mysqli->query("SELECT code,
time
FROM `match`
WHERE referee_code IN (SELECT code
FROM referee)");
$completeData=array();
while ($row2 = $result2->fetch_array())
{
$completeData[] = $row2;
}
print_r($completeData);
Don forget to accept answer if it helps :)
I'm trying to do a little text formatting and query the SQL all in one hunk of code. Previously, it was doing the listing just fine without formatting, but I need to replace underscores with spaces and remove the category that precedes each string for the purposes of user readability.
<?php
//doing the query
$query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query parts table!");
while($row=mysql_fetch_array($result)) {
//explode removes the preceding category, str_replace obviously replaces the _
$labelCPU = explode(':',str_replace('_',' ',$row['itemName']));
//displays the option in HTML
$aa .= "<option value='{$row['partID']}'>$labelCPU</option>";
}
?>
<select name="cpu"><? echo $aa; ?></select>
When it echoes the variable in the list, I can tell the query is still executing fine because I am getting the appropriate number of options, but they all display as "Array".
Where am I going wrong here?
Your line below:
$labelCPU = explode(':',str_replace('_',' ',$row['itemName']));
Is changing it into an array. Explode basically takes a string and converts it to an array splitting it by the character you specify (in this case ':').
You need to do something like:
for ($i=0; $i<count($labelCPU); $i++) {
$aa .= "<option value='{$row['partID']}'>$labelCPU[$i]</option>";
}
I suspect you are using explode to get the category name after ":". So perhaps this would work better:
$aa .= "<option value='{$row['partID']}'>$labelCPU[1]</option>";
php function explode returns an array.
Place
var_dump($labelCPU);
after explode statement. It will dump all the data stored in $labelCPU. Then find the element which holds your desired data
Switch out for mysql_fetch_assoc if you aren't using numeric keys, you're also just missing an index on what you've exploded (I added a comment).
Note that the mysql_fetch_assoc/array are being deprecated in favor of PDO. Might want to consider switching out if longevity is a concern.
<?php
$query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query parts table!");
$aa = "";
while($row = mysql_fetch_assoc( $result ) )
{
$labelCPU = explode(':',str_replace('_',' ',$row['itemName']));
$labelCPU = $labelCPU[1]; // this is what you're missing
$aa .= "<option value='{$row['partID']}'>$labelCPU</option>";
}
?>
<select name="cpu"><? echo $aa; ?></select>
Good luck!
I've created this thing to get a TEXT value from my database.
$query1 = "SELECT * FROM `ma_apps` WHERE `assignedto`='$_SESSION[username]'";
$result1 = mysql_query($query1) or die(mysql_error());
$Appdata = mysql_fetch_array($result1) or die(mysql_error());
and then:
$app_content = $Appdata['1'];
echo $app_content;
but it echos and says nothing, although it's the right name of the key. And I already checked if I can get another value from the database from a key that is considered as "TINYINT", and it works well. But I fail to echo/get the "TEXT" keys from my database.
Thanks.
i think you want to access to the second value in the array.
try this
$Appdata[1];
otherwise use mysql_fetch_assoc to create a array with the field name as key
If your string resembles an HTML tag then it's going to be treated like an HTML tag and not show as a string on the screen. It's worth checking view source on your browser to see if your string starts with a <.
$query1 = "SELECT * FROM `ma_apps` WHERE `assignedto`='{$_SESSION['username']}'";
Also,
$Appdata[1];
try echo $Appdata[0]; because you are asking for a column with name '1', vs asking for the index 1
You should do
$query1 = "SELECT * FROM `ma_apps` WHERE `assignedto`='".$_SESSION[username]."'";
and
$app_content = $Appdata[0];
var_dump($Appdata) check the values inside the variable and use it properly. Index is without '.
you can also just echo everything from the result set with:
<?php
mysql_data_seek($result1,0);
while ($row = mysql_fetch_array($result1)){
foreach ($row as $key => $value){
echo $key." - ".$value;
}
}
?>
Then you will see the key value pairs
How can I avoid duplicate return data with MYSQL with autosuggest with this code?
Thank you so much for helping
<?php
include('conn.php');
$str = strtolower($_GET['content']);
if(strlen($str))
{
$sel = mysql_query("select * from Streams where title like '".trim($str)."%'");
if(mysql_num_rows($sel))
{
echo "<table border =\"0\" width=\"100%\">\n";
if(mysql_num_rows($sel))
{
echo "<script language=\"javascript\">box('1');</script>";
while($row = mysql_fetch_array($sel))
{
$country = str_ireplace($str,"<b>".$str."</b>",($row['title']));
echo "<tr id=\"word".$row['title']."\" onmouseover=\"highlight(1,'".$row['title']."');\" onmouseout=\"highlight(0,'".$row['title']."');\" onClick=\"display('".$row['title']."');\" >\n<td>".$country."</td>\n</tr>\n";
}
}
echo "</table>";
}
}
else
{
echo "<script language=\"javascript\">box('0');</script>";
}
?>
What I can see in your code is that there is only a single field - title - from the SQL resultset that you are using in the PHP code. So why not instead write your query as:
"SELECT DISTINCT `title`
FROM Streams
WHERE title like '".trim($str)."%'"
Or perhaps if you can't change the query, you may store the title in a PHP array and then run array_unique on it to avoid duplicates before writing them to HTML.
From looking at your code, it seems like you're only using the "title" field from your database. You could do this:
$sel = mysql_query("SELECT DISTINCT title FROM Streams WHERE title LIKE '".mysql_real_escape_string(trim($str))."%'");
As per the MySQL documentation:
The [...] DISTINCT options specify
whether duplicate rows should be
returned. [...] DISTINCT specifies
removal of duplicate rows from the
result set. It is an error to specify
both options.
Ideally you need to select distinct elements
mysql_query("SELECT DISTINCT(title) FROM Streams WHERE title LIKE '".mysql_real_escape_string(trim($str))."%'");
Ofcourse if any reason you cant do that,
Put the data in a array and check if it was previously added to prevent duplication, define array outside the while
$data = array()
if (!in_array($row["title"], $data)){
\\do your thing
array_push($data, $row["title");
}