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.
Related
I have this text string varchar type i get from database echo.
how to extract it and count the value :
in the database it save as string ["1","2","3"] in varchar.
how to count this as 3 item using php?
my sql code is :
$sql2 = "SELECT * FROM il_dcl_stloc1_value WHERE record_field_id = '$exc_prt_id'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$exc_prt_id1 = $row2['value'];
echo "$exc_prt_id1"; // this will result ["1","2","3"]
}
There are tons of ways you can do this, but if you just care about the count, not the values, and they will always come in this format, you can just use
$count = count(explode(",", $exc_prt_id1));
You can also do a
$count = count(json_decode($exc_prt_id1));
If you want the values, run the above code without the count.
$arr = json_decode($exc_prt_id1);
This will result in a PHP array.
While the 2nd option is generally preferred and is better practice, the 1st one might be of use in certain cases. If there is anything unclear, just ask :)
Try this way
$exc_prt_id1= str_replace("[","",$exc_prt_id1);
$exc_prt_id1= str_replace("]","",$exc_prt_id1);
$exc_prt_id1= str_replace('"','',$exc_prt_id1);
$invoiceArr = explode(",",$exc_prt_id1);
$count = count(explode(",", $invoiceArr ));
I'm using this script to get data from a database
$sql = "SELECT * FROM items WHERE catid = 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo $row['extra_fields'];
}
The output is:
[{"id":"1","value":"johndoe"},{"id":"2","value":"marydoe"}]
I want to extract/print only the value corresponding to "id":"1" (that in this case is 'johndoe'). I'm not able to extract it from the above data type.
To read JSON in PHP use
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields'];
// Do something with $array['id']
}
Did you realise you can directly go for that data in MySQL?
SELECT value FROM items WHERE id = 2;
edit:
Basically your query is
SELECT comma-separated column names or star for all, use only what you really need to save bandwidth, e.g. SELECT id, value
FROM table-name, e.g. FROM mytable
WHERE columnname = desired value, e.g. WHERE id = 2
You want to query only the required columns in the required rows. Imagine one day you would have to parse 1 million users every time you want to get an id... :)
The output is JSON. Use PHP's json_decode function.
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields']);
foreach($array AS $item) {
echo $item['id'];
}
}
Currently this is the code that fits my needs:
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields']);
$value = $array[0]->value;
}
You should do it in the mysql query part. For example, set the ID = 1 in the query.
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 been searching for a few hours to find the right way to do this. Any help would be greatly appreciated.
I am looking for a way to count the number of fields that are NOT NULL in a defined row.
I would like to use mysql_query to convert the row into an array, skipping the empty fields. Then I want to take that array and find its size.
mysql_query(SELECT * FROM table)
$value = array(list, of, values, from, row, in, my, database);
echo sizeof($value); //value would be 8
I have also tried counting the fields using mysql_num_fields(), but don't know how to subtract the empty fields from the results.
$test = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_fields($test);
echo $num_rows; //but subtracting all fields that are NULL
Thank you in advance for your help.
An easier way to clean arrays is to use php's array_filter function without a callback parameter. By default that function is set to remove elements that contain a false (or a 0), null or a "".
//This prunes out 'false', '0', 'null' or ''
$my_array = array_filter($my_array);
First store the mysql row into array and then filter it and then count element using cont function
$result = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($result))
{
$row = array_filter($row); //remove empty values
$num_of_values_non_empty = count($row);
echo $num_of_values_non_empty;
}
I have a mysql table with columns id, f1, f2, f3, ..., f20 where id is productID and f1,...f20 are product features. Depending on each product, some might have all, none or only some columns filled.
Each column holds a delimited string like a#b#c#d where a,b,c,d are values in different languages (a=english, b=french etc)
I need to select a row by it's id, explode each column's value (f1,f2...) with '#' in order to get the language part I need and then pass the values to an array in order to use in my product spec page.
How do I loop through the fetched row (i'm using $row = my_fetch_array) and put the exploded value into a one dimension array like $specs=('green', 'M', '100', 'kids'...) etc?
PS:I know, is complicated but I cant come up with a better idea right now.
Try this:
$result = mysql_query("...");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$arr = array();
foreach ($row as $k=>$v)
{
$features = explode("#", $v);
$value = $features[1]; // get the specific language feature
$arr[] = $value;
}
$specs = join(", " , $arr);
}
Not sure this is the best way togo but you could define an array with your langs, then access the result by lang
<?php
$langs=array('eng'=>0,'fr'=>1,'ger'=>2,'geek'=>3);
while ($row=mysql_fetch_assoc($result)) {
$specs=explode('#',$row['f1']);
$other=explode('#',$row['f2']);
...
}
//Get lang from cookie that you could set elsewhere
$lang=(isset($_COOKIE['lang']))?$_COOKIE['lang']:'eng';
echo $specs[$langs[$lang]];
?>
My solution for how I understand you question:
// Make a MySQL Connection
$sQuery = "SELECT f1,f2,... FROM table WHERE id = ...";
$oResult = mysql_query($sQuery) or die(mysql_error());
//Fetch assoc to use the column names.
$aRow = mysql_fetch_assoc($oResult);
//Prepare the product properties array
$aProductProperties = array("English"=>array(),"French"=>array(),"Dutch"=>array());
//Loop over all the columns in the row
foreach($aRow as $sColName=>$sColVal){
//Explde the column value
$aExplodedCol = explode("#",$sColVal);
//The code below could be nicer when turned into a looped that looped over every language,
//But that would make the code less readable
$aProductProperties['English'][$sColName] = $aExplodedCol[0];
$aProductProperties['French'][$sColName] = $aExplodedCol[1];
$aProductProperties['Dutch'][$sColName] = $aExplodedCol[2];
}
//Done, you should now have an array with all the product properties in every language