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!
Related
I'm trying to run a MYSQL query inside a foreach loop.
here's the scenario:
I have a comma separated string with some names in it.
I use explode() and foreach() to get the separate values/names from this comma separated string.
Then I need to search mysql database for each of these values/names that I get from this string and if that value exists in the database, I then get its ID and create a new recrord in another table in the database.
However, when I run my code, I only get the ID of the first instance from the comma separated string.
my mysql database looks like this:
id category_name
3 Hotel
4 Restaurants
This is my code:
//My comma separated string///
$biz_cat = 'Hotel, Restaurants';
///i do the explode and foreach here///
$arrs = explode(',', $biz_cat);
foreach($arrs as $arr){
$sql99 = "SELECT * FROM categories WHERE category_name='$arr'";
$query99 = mysqli_query($db_conx, $sql99);
while($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)){
$catIDS = $row99['id'];
}
//this is where i need to insert my new data in different tabel.
echo $catIDS.'<br>;
}
so when the i run my code, I get the ID of the Hotel twice like so:
3
3
I'm expecting it to be like below based on what I have in MYSQL:
3
4
Could someone please advice on this issue?
First of all such things should be done using prepared statements. Not only it is easier and faster, but also more secure. Remember to always use prepared statements.
//My comma separated string///
$biz_cat = 'Hotel, Restaurants';
$stmt = $db_conx->prepare('SELECT * FROM categories WHERE category_name=?');
$stmt->bind_param('s', $cat);
foreach(explode(',', $biz_cat) as $cat){
$cat = trim($cat); // remove extra spaces at the beginning/end
$stmt->execute();
// we fetch a single row, but if you expect multiple rows for each category name, then you should loop on the $stmt->get_result()
$row99 = $stmt->get_result()->fetch_assoc();
// echo it in the loop or save it in the array for later use
echo $row99['id'];
}
In the example here I prepare a statement and bind a variable $cat. I then explode the string into an array on which I loop straight away. In each iteration I execute my statement, which in turn produces a result. Since you seem to be interested only in the first row returned, we do not need to loop on the result, we can ask for the array immediately. If you would like to loop just replace
$row99 = $stmt->get_result()->fetch_assoc();
with
foreach($stmt->get_result() as $row99) {
echo $row99['id'];
}
Once you get the id in the array, you can either print it out or save it into an array for later use.
As of now, you are re-assigning a new value to scalar variable $catIDS for each record returned by the query, then you echo it one you are done looping. You would need to put the echo/insert logic inside the loop (or maybe store the values in array).
Another thing to note is that you are splitting with , (a single comma), but you have a space between the two words. As a result, the second value (Restaurant) starts with a space, which will cause the query to return an empty resultset. You probably want to split with , (a comma followed by a space).
$biz_cat = 'Hotel, Restaurants';
$arrs = explode(', ', $biz_cat);
foreach($arrs as $arr){
$sql99 = "SELECT * FROM categories WHERE category_name='$arr'";
$query99 = mysqli_query($db_conx, $sql99);
while($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)){
$catIDS = $row99['id'];
//this is where i need to insert my new data in different tabel.
echo $catIDS.'<br>';
}
}
The code below can do what you need.
Update INSERT YOUR NEW DATA HERE
$biz_cat = 'Hotel, Restaurants';
$arrs = explode(',', $biz_cat);
foreach ($arrs as $arr) {
$query99 = mysqli_query($db_conx, "SELECT * FROM categories WHERE category_name='$arr'");
while ($row99 = mysqli_fetch_array($query99, MYSQLI_ASSOC)) {
$catIDS = $row99['id'];
// INSERT YOUR NEW DATA HERE
echo $catIDS . '<br/>';
}
}
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'];
}
I'm trying to pull an array to use on another query but it's not working, because the last comma.
<?php
include"connection.php";
$pos = mysqli_query($not,"SELECT * FROM equipos");
$logos = array();
while($row= mysqli_fetch_assoc($pos)){
$logos[] = "<br>'".$row['abrv']."'=>"."'".$row['logo']."'";
}
$logos = implode(",", $logos);
$enjuego = mysqli_query($not,"SELECT * FROM partidos WHERE dprt='ftbls'");
while($part=mysqli_fetch_array($enjuego)){
$liga=$part['serie'];
$eq1= $part['eq1'];
$eq1s= strtoupper($eq1);
$eq2= $part['eq2'];
$eq2s= strtoupper($eq2);
echo $logos[$eq1].'<br>';
}
?>
It gives me the same error over and over again.
This is the closest I came but just doesn’t work.
Can someone tell me what am I doing wrong?
The error I get is: Warning: Illegal string offset 'gua' in line 22
You have several problems with your code:
You never created an array
You constantly overwrite $logos
Your usage of substr_replace() indicates a deeper problem.
Here's a better approach:
Build the array.
$logos = array();
while($row= mysqli_fetch_assoc($pos)){
$logos[] = "<br>'".$row['abrv']."'=>"."'".$row['logo']."'";
}
There are many ways condense an array into a string. I encourage you to browse the manual on PHP Array Functions. In your case, you are interested in implode()
$logos = implode(",", $logos);
Note: The value for $logos smells. You should construct your arrays to hold data, not formatting.
For example:
$logos[$row['abrv']] = $row['logo'];
Output:
print_r($logos);
What you want can be achieved in many ways, but let's look at your code, there are quite a few things wrong in there.
Semantically meaningless variable names like pos, not, equipos, abrv. Only logo and result are good variable names.
Using the * selector in database queries. Don't do that, instead select the exact fields you need, it's better for performance, maintainability, code readability, testability, ... need I say more?
Fetching per row and running code on each row when what you actually want is an array containing all rows. Solution:
$result = mysqli_query($not, "SELECT * FROM equipos");
$logos = mysqli_fetch_all($result, MYSQLI_ASSOC);
Concatenating subarrays by using strings, that's not how it works, what you could do:
while($row = mysqli_fetch_assoc($result))
{
$logos[][$row['abrv']] = $row['logo'];
}
But as I said, that's not necessary.
Overwriting your variable $logos with each iteration of the loop. You'd need to do $logos[] = ....
Typically, implode is useful for such cases.
Without knowing what exactly you want to do, take this as a first hint:
$logos = array();
while($row= mysqli_fetch_assoc($pos)){
$logos[] = "<br>'".$row['abrv']."'=>"."'".$row['logo']."'";
}
$logos = implode(",", $logos);
The simplest way I would have thought is just to change the query and fetch the array into that -
<?php
include_once("connection.php");
$result = mysqli_query($not,"SELECT abrv, logo FROM equipos");
$rows = mysqli_fetch_array($result, MYSQLI_ASSOC);
// display the result
echo "<pre>"
print_r($rows);
echo "</pre>"
?>
I've read through some other posts that were similar but I can't seem to get a good implementation of them. I'm calling a php script from another program that needs the results returned in one variable, space or comma separated. The php connects to a db (no problem there) and runs a query that will return 2 to 6 or so matching rows. I need those results together in one variable but can't seem to get it.
Here's where I'm stuck.
$t = "SELECT user FROM call_times WHERE client='$clientid' AND start <= $date AND end >= $date";
$result = mysql_query($t) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$temp = $row['user'];
}
echo $temp;
The query runs fine, but you can see from the code what I'm trying (and failing) to do in the lower part. I need $temp to hold a list of results (ex: 5567889 57479992 4335780 (each of which is a different entry in user column)).
Thanks so much!
$array = array();
while ($row = mysql_fetch_array($result)) {
$array[] = $row['user'];
}
$string = implode(" ", $array);
Now $string has the space-separated values of the user column.
Good luck!
Try group_concat() and you won't need PHP to manipulate the results.
supposed a variable named $xlnum value is as this 20,4,56,987,68,96.....the variable $xlnum value is input by the vistor.
the next i will passed the value to a sql query. if the value is one. that i can know how to do it. eg:
$result=mysql_query("select nid,title form node where nid=20");
while($row = mysql_fetch_object($result)) {
echo $row->nid;
echo $row->title;
}
but now the value is 20 4 56...,i want to loop out all the nid and title of 20,4,56,987,68,96.....how do i do.
why not using WHERE ... IN
where nid in (2,3,4.....)
if $xlnum is an array you could do something like this:
$result=mysql_query("select nid,title from node where nid in (".implode(',',$xlnum).")");
while($row = mysql_fetch_object($result)) {
echo $row->nid;
echo $row->title;
}
If $xlnum is really just a string with comma separated numbers then just put the $xlnum inside the () without imploding.
In short:
$result = mysql_query("select nid,title form node where nid IN ($xlnum)");
But you need to validate that it contains sane values.
Assume $xlnum = '20,4,56,987,68,96'; in these examples. Both end up with $sql that you can pass to mysql_query.
Option 1
// remove white space
$xlnum = preg_replace('/\s+/', '', $xlnum);
// make sure the string is nothing but numbers separated by commas
if (!preg_match('/^(\d+,)*\d+$/', $xlnum))
die("invalid format");
$sql = "select nid,title form node where nid IN ($xlnum)";
Option 2
$nids = array();
// loop through each comma delimited value
foreach (explode(',', $xlnum) as $nid)
{
// force the value to an integer
$nid = (int) $nid;
// if it is non-zero add it to the list
if ($nid) $nids[] = $nid;
}
// if the array is empty, nothing valid was entered
if (!$nids)
die("invalid format");
// recreate the comma delimited string
$xlnum = implode(',', $nids);
$sql = "select nid,title form node where nid IN ($xlnum)";
These are just two different ways to make sure the input is valid. The second is slightly different in that it will just ignore the pieces that are invalid.
I prefer something more like the second since it's easy to accidentally mess up a regular expression.