Add values into array - php

This code is reading from mysql db tables and should return few names. But each name is sent as separated string. I need it in one string. Here is code:
<?php
session_start();
function prList($REQUEST){
include ('into_sql.php');
mysql_select_db("db394771350", $conn);
$usr = $REQUEST["usnm"];
$fID = $REQUEST["friendID"];
$sql = mysql_query("SELECT * FROM users WHERE username='$usr'");
$a=mysql_fetch_array($sql);
$uID = $a["id"];
$res1 = mysql_query("SELECT * FROM friends WHERE friendID='$uID' AND accept='0'");
while($b=mysql_fetch_array($res1)){
$fuID = $b["userID"];
$res2 = mysql_query("SELECT * FROM users WHERE id='$fuID'");
while($c=mysql_fetch_array($res2)){
$usrn = $c["username"];
$array = array("$usrn");
encode($array);
}
}
}
?>
This is output:
["rhys"]["alexroan"]["bobjosh"]["xc.j.gingex"]["tom"]

$usrn = "";
while($c=mysql_fetch_array($res2)){
$usrn .= $c["username"];
}
echo $usrn;

How is the function encode defined?
I would suggest replacing $array = array("$usrn"); by $array[] = $c["username"] and at the end just implode all entries into one string via `$string = implode($array)

Why don't you just concatenate results ?
$result = "";
$i = false;
while ($c=mysql_fetch_array($res2)){
if ($i)
$result .= ' ';
$result .= $c["username"];
$i = true;
}
echo $result;

Check this out may be helpfule forl
FIND_IN_SET(str,strlist)
Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by “,” characters. If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic. Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL. This function does not work properly if the first argument contains a comma (“,”) character.
mysql> SELECT FIND_IN_SET('b','a,b,c,d');
-> 2

Related

Array to string conversion failed in PHP

I have a query which fetches distinct user ids and I am trying to convert it into a comma separated string which I can pass into another sql query having IN in WHERE clause.
But I am getting an error saying array to string conversion.
$qry0="SELECT DISTINCT id FROM users ";
$res0=getData($qry0);
while($row0=mysqli_fetch_array($res0))
{
$data0 = $row0['id'];
}
And I'm trying to convert it as string like this:
$array = explode(",", $data0);
and pass it to another
$qry="SELECT * FROM login WHERE clientid IN(".$array.") ";
USe implode instead of explode:
$qry0="SELECT DISTINCT id FROM users ";
$res0=getData($qry0);
$data0 = array(); // initialize array first
while($row0=mysqli_fetch_array($res0))
{
$data0[] = $row0['id']; // create array like this
}
$array = implode(",", $data0); // use implode to convert array to string
The explode() function breaks a string into an array.To break array into string you need to use implode()
$qry0="SELECT DISTINCT id FROM users ";
$res0=getData($qry0);
$data0 = array();
while($row0=mysqli_fetch_array($res0))
{
$data0[] = $row0['id'];
}
$array = implode(",", $data0);

How to extract comma separated column values from database using php

In my database table there is a column named 'marks' . it contains values like 50,55,67,88,...
Now I need to read this values one by one like - first 50, then 55 and so on. How is it possible using php ?
include("db_connect.php");
$result = mysql_query("SELECT * FROM students ",$con);
while($rows = mysql_fetch_array($result))
{
$mark1=$rows['marks'];//what will do here
$mark2=$rows['marks']; //should get value 55 and so on
}
If your values are comma separated then explode the field.
http://php.net/manual/en/function.explode.php
include("db_connect.php");
$result = mysql_query("SELECT * FROM students", $con);
while($rows = mysql_fetch_array($result)) {
$mark=explode(',', $rows['marks']);//what will do here
foreach($mark as $out) {
echo $out;
}
}
Explode the data from the database. Use the explode function.
Access using indexes
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
$mark1 = $exp[0]; //result is 50
$mark2 = $exp[1]; //result is 55
$mark3 = $exp[3]; //result is 67
}
Or loop using foreach
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
foreach($exp as $mark) {
echo $mark;
}
}
If that row contains ,, the just use explode():
while($rows = mysql_fetch_assoc($result)) {
$mark1 = explode(',', $rows['marks']); // should contain the comma separated values
// in array form
// then loop again
foreach($mark1 as $mark_piece) {
// do something here
}
}
You should use the explode function
$marks = explode(",", $rows['marks']);
foreach($marks as $mark){
//your code to do something with the mark.
}
N.B. explode() function breaks the string into array, it accepts three arguments, first one is the delimiter that specifies where to break the string, second one is the string that needs splitting, and third one is not mandatory but it tells how many array to return.
$str_to_exploade = 'This,string,needs,some,exploiting';
$explode_string = explode(',', $str_to_exploade);
echo '<pre>';
print_r($explode_string);
echo $explode_string[0].'<br/>';
echo $explode_string[1];
More about explode() go to : http://php.net/manual/en/function.explode.php

search array of words in database

I have text :
$a = I wanna eat apple , and banana .
I wanna get every words and punctuation of that sentence :
$b = explode(' ', strtolower(trim($a)));
the result of explode is array.
I have a words table on db that has fields : id, word and typewords all in lowercase. but for punctuation there are no exist in db.
I wanna search every words in db to take the type of words, so the final result that i want to get is :
words/typeofwords = I/n wanna/v eat/v apple/n ,/, and/p banana/n ./.
here's the code :
function getWord ($word){
$i = 0 ;
$query = mysql_query("SELECT typewords FROM words WHERE word = '$word' ");
while ($row = mysql_fetch_array($query)) {
$word[$i] = $row['typewords'];
$i++;
}
return $word;
}
echo $b.'/'.getWord($b);
but it doesn't work, please help me, thanks !
Try with this:
function getWord($words){
$association = array();
foreach($words as $word)
{
$query = mysql_query("SELECT typewords FROM words WHERE word = '$word' ");
if($row = mysql_fetch_array($query))
$association[$word] = $row['typewords'];
elseif(preg_match('/[\.\,\:\;\?\!]/',$word)==1)
$association[$word] = $word;
}
return $association;
}
$typewords = getWord($b);
foreach($b as $w)
echo $w.'/'.$typewords[$w];
function getWord($word){
// concat the word your searching for with the result
// http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat
$query = mysql_query("SELECT CONCAT(word,'/',typewords) as this_result FROM words WHERE word = '$word' ");
$row = mysql_fetch_array($query);
return $row['this_result']." "; // added a space at the end.
}
// loop through the $b array and send each to the function
foreach($b as $searchword) {
echo getWord($searchword);
}
You assume the function parameter to be an array, but it is a string.
Edit: In your function you treat $word as an array as well as a string. Decide what you want and recode your function.

PHP - Delete last 2 characters in a loop

I have the following which produces results for me.
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
echo $author['fullname'] .', ';
}
It prints it out perfect, except on the last run it still adds the comma and space, is there a way i can strip this from the last result, so its:
name, name, name, name
Instead of the following
name, name, name, name,
Cheers
A better way of doing this would be to separate out the handling of database results from the view/output logic, and then you can sidestep the issue all together, using implode to allow PHP to join each of your authors together into a single string, split by your delimiter of a comma and a space:
// your loop {
$authors[] = $author['fullname'];
}
// your output
echo implode(', ', $authors);
Just concate the data into a string and then remove the last 2 chars using
$author['fullname'] = substr($author['fullname'], 0, -2);
Refer the manual for substr http://php.net/manual/en/function.substr.php
Instead of echoing each author out you could put them in a string and then simply use trim() to take off the trailing comma and finally echo the whole string.
this will probably work
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
//echo $author['fullname'] .', ';
}
$name_count = count($author[]);
for($x=0;$x<$name_count ;$x++){
if($x == $name_count -1){
echo $author['fullname'];
}else{
echo $author['fullname'].", ";
}
}
the idea is to detect the last array index, so that we can apply all the commas after each name except to the last one.
don't ever echo inside foreach
$var = '';
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
$var .= $author['fullname'] .', ';
}
echo trim($var,', ');

PHP - Compare exploded word with mysql varchar in PHP

How can I compare exploded word with mysql varchar in PHP?
This code produce what i want but it also give this error
veranderenwachtwoordjij
Fatal error: Call to a member function fetch_assoc() on a non-object......
$word = "Also, to be safe, change your password regularly... you don't have to be obsessive about it: every three hours or so should be enough. And because erring on the side of caution is always a good idea, fake your own suicide and change your identity at least once a year.";
$pieces = explode(" ", $word);
$x = 0;
while($x < word_count($word)) { // word count function returns int (51)
$aPiece = $pieces[$x]; // change $pieces[$x] to 'you' and then it works
$result = $conn->query("SELECT * FROM dict WHERE english='$aPiece'");
$z = 0;
while($z < $num_result) // $num_result returns amount of rows in database
{
$row = $result->fetch_assoc(); //error line is here
echo stripslashes($row['dutch']);
$z++;
}
$x++;
}
I guess the problem comes from the don't in your test sentence : you forgot to escape quotes with a function like mysql_real_escape_string.
For example :
$aPiece = mysql_real_escape_string($pieces[$x]);
$result = $conn->query("SELECT * FROM dict WHERE english='$aPiece'");
I think
$row = $result2->fetch_assoc();
should be
$row = $result->fetch_assoc();
since you don't seem to have a $result anywhere.
$result2 in $result2->fetch_assoc(); is not the correct variable, it should be
$result->fetch_assoc();
by the way you have to delete the punctuation marks in order to find the words in your database (I think) one of your first lines should (before the explode) be similar to this:
$words = strtr($words, ',.:!','');

Categories