I want to make a web service and I want to return only one row and set the values of the row in a chain like: value1; value2; value2; ie separated; each column of the row
I have written this code:
$query = "SELECT * FROM base WHERE id =" $id;
$result = mysql_query ($query, $link);
$row = mysql_fetch_array ($result);
but I do not now how to put a string value of each row separated by;
Can anyone help? thank you
Use foreach loop.
$values = '';
foreach ( $row as $value ){
if ( $value == end($row) )
$values .= $value
else
$values .= $values .';';
}
Related
I am using PDO in order to select some values from my database.
For each iteration of my $teachArray, I store the selected array into my $language_id variable. I then get rid of any empty array that I have inside my $language_id and assigning it to my $NoEmptyArray_language_id However, I am only storing the last array inside of $language_id in $NoEmptyArray_language_id.
I would like to concatenate every array in $language_id into $NoEmptyArray_language_id.
I cannot use $NoEmptyArray_language_id .= $language_id; since it will give me an error: Array to String conversion
Here is my simple query.
$sqlFindId = "SELECT language_id
FROM language_skill
WHERE person_id = :person_id AND language_learning = :language_learning AND language_id = :language_id";
$NoEmptyArray_language_id = "";
foreach ($teachArray as $dataTeach)
{
$query = $handler->prepare($sqlFindUser);
$query->bindValue(':person_id', $_SESSION['person_id']);
$query->bindValue(':language_learning', 1);
$query->bindValue(':language_id', $dataTeach);
$query->execute();
$language_id = $query->fetchAll(PDO::FETCH_COLUMN, 0);
if ( count( $language_id ) != 0 ) {
$NoEmptyArray_language_id .= $language_id;
}
}
print_r($NoEmptyArray_language_id);
You have to define $NoEmptyArray_language_id = array();
Also change code with $NoEmptyArray_language_id[] = $language_id;
Now you have array with values in $NoEmptyArray_language_id.
If you want to get string convert this array to string using implode function.
I have made MySQL database with three columns tags_id,tags,user_id, it must give out all the tags with respect to the user_id given.
eg: for this link:"http://allwaysready.16mb.com/Cuboid/tagsTest.php?user_id[]=7"
Output is:
{"result":[{"tags":"Pascol"},{"tags":"PHP"},{"tags":"Python"}]}
But I need my result to be in a sing string like this:
{"result":[{"tags":"Pascol","PHP",","Python"}]}
It should not be in array i want it in a single string.
Here is my php code :
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$user_id = $_GET['user_id'];
require_once('dbConnect.php');
$user_tags = array();
foreach ($_REQUEST['user_id'] as $key => $val) {
$user_tags[$key] = filter_var($val, FILTER_SANITIZE_STRING);
}
$user_ids = "'" . implode("','", $user_tags) . "'";
$sql = "SELECT * FROM user_tags WHERE user_id IN ({$user_ids})";
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"tags"=>$row['tags']
));
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
}
what should i change in my code.?
please help me guys thank you.
Your array_push mean
Push to your array new element with $key => $value
So solution in this case is remove array_push and try
$result['tags'][] = $row['tags'];
This seems like it should be really straightforward, but I keep getting unexpected output. I'm trying to access specified rows in a SQL database which each contain a numerical value and then calculate the sum of those values. PHP is concatenating the values as if they were strings even after I've set the datatype of the values to float. My code:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
$population_value = is_array($population_value) ? $population_value : array($population_value);
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I have also tried:
$total = array("");
foreach($population_value as $value){
floatval($value);
array_push($total, $value);
echo $value;
}
echo array_sum($total);
My output is always something like: 100002000030000
with 10,000 20,000 and 30,000 being the values of each population.
I've successfully calculated sums using foreach with values that weren't retrieved from MySQL.
What is going on here?
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
//This is actually rewriting the array or NOT adding the value to it.
$population_value = is_array($population_value) ? $population_value : array($population_value);
//ok, so you're going to repeatedly output this?
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I think what you want is this:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
$population_value=array(); //Initialize the array so we can just add to it.
while($row = mysqli_fetch_assoc($result)) {
$population_value[]= intval($row['population_value']); //Just making sure we get a number.
echo end($population_value); //We could output the row again, or just grab the last element of the array we added.
}
//Now that the array is fully populated and we've made sure it's only numbers, we output the grand total.
echo array_sum($population_value);
First, don't initialize the array with an empty string. Do this instead:
$total = array();
or with the new style:
$total = [ ];
Second, rewrite the floatval thing like this:
array_push($total, floatval($value));
That should fix it...
I am trying to get the matched rows from a table and save it in a Global Array so that I can use it in different functions.
But when I do print_r of that array it shows only last row.
Here is my code
function setCampoFeed()
{
echo $sql = "SELECT campofeed.tag,campofeed.registro,campofeed.valor FROM campofeed ".
"INNER JOIN registrofeed ON registrofeed.id = campofeed.registro ".
"WHERE registrofeed.feed='".$this->idFeed."'";
$result= $this->localDb->execute($sql);
$this->campoFeed= mysql_fetch_array($result))
}
So here campoFeed is the array that should have all the rows of the match, but now its just having the last row.
Thanks in advance
Use
$this->campoFeed[] = mysql_fetch_array($result);"
insted of
$this->campoFeed= mysql_fetch_array($result);
You will get all data in array
Try this one if it works for you..
$resultArray = array();
$campoFeed = array();
$resultArray = mysql_fetch_array($result);
foreach($resultArray as $key => $value){
$campoFeed[$key] = $value;
}
print_r($campoFeed);
Use this
$mergedArray=array();
while($data= mysql_fetch_array($result)) {
$final_array = unserialize($data['data']);
$mergedArray=array_merge($mergedArray,$final_array);
}
array_unique($mergedArray, SORT_REGULAR);
Having trouble getting all match results for a particular session ID. I want to not include the session ID but include all other results for now (then will add conditions in php). I am just getting the rows for one ID (128). So if the session ID is 125, it excludes this but only picks up 128 which is first in the records but after three 128 entries (for three questions) is an ID 127 that does not get included. When printing the count it tells me 3, there should be 6. So I assume the problem is within the function.
Any ideas how to push this through? Here's my function:
function quiz_match($user_id, $question_id ,$choice_id){
$query = mysqli_query($_POST['x'], "SELECT * FROM `question_answers` WHERE `user_id` <> $user_id AND `question_id` = $question_id AND `choice_id` = $choice_id" );
while($row = mysqli_fetch_assoc($query)){
$rows[] = $row;
if (count($rows)>0){
foreach ($rows as $key => $value) {
$u_id = $value['user_id'];
$array_q= [];
array_push($array_q, $u_id, $value['question_id'], $value['choice_id']);
//$result = count($array_q);
//echo "number of rows " . $result;
} return $array_q;
} else return false;
}
}
*For the array [0] is the ID, 1 question id and [2] choice id.
Your problem stems from bad indenting, causing you to not realize where you were throwing the code: whether it was in the while loop, the if, the foreach, would have been totally a mystery.
Therefore, you had your if-statement inside your while loop, and thus were returning from within the while loop, rather than adding all the rows to the $rows array and then doing your if-statement.
You also would have been resetting the $array_q to empty, if you weren't returning prematurely, so that line needs to be moved out of the foreach loop.
You also have no MySQL connection being passed into the function! You're treating $_POST['x'] as if its a MySQL connection, and there's no way that it is!
function quiz_match($connection, $user_id, $question_id ,$choice_id)
{
//there is no way the next commented out line even works!
//$query = mysqli_query($_POST['x'], "SELECT * FROM `question_answers` WHERE `user_id` <> $user_id AND `question_id` = $question_id AND `choice_id` = $choice_id" );
$query = mysqli_query($connection, "SELECT * FROM `question_answers` WHERE `user_id` <> $user_id AND `question_id` = $question_id AND `choice_id` = $choice_id");
$rows = array(); //you should add this too
while($row = mysqli_fetch_assoc($query))
{
$rows[] = $row;
}
if (count($rows)>0)
{
$array_q = array(); //this should be here, not in the foreach loop
foreach ($rows as $key => $value)
{
$u_id = $value['user_id'];
//$array_q= []; //wrong place for this
array_push($array_q, $u_id, $value['question_id'], $value['choice_id']);
}
//$result = count($array_q);
//echo "number of rows " . $result;
return $array_q;
}
return false;
}