mysql query for each of the values of an array - php

for ($i=0; $i<=$gsayi-1; $i++)
{
$a[] = mysql_result($aylik,$i);
}
foreach ($a as $value)
{
$m = mysql_query("SELECT puan FROM sorular WHERE ID = $value");
echo $m;
}
a[ ] array is
2,2,1
I am trying to execute a mysql query with each of that values. I am using that values as ID.
I tried foreach loop but it shows me Resource id #7Resource id #7
How can I solve this problem?

You have to fetch the result
$m = mysql_query("SELECT puan FROM sorular WHERE ID = $value");
$result = mysql_fetch_assoc($m);
echo $result['puan'];

You have to get the results in some form.
http://php.net/manual/en/function.mysql-query.php
mysql_query returns a resource...not the results of the query. To get the results you have to use one of the mysql_fetch_* functions, in this example we fetch an object with the query results.
http://www.php.net/manual/en/function.mysql-fetch-object.php
Try something like this:
for ($i=0; $i<=$gsayi-1; $i++) {
$a[] = mysql_result($aylik,$i);
}
foreach ($a as $value) {
$result = mysql_query("SELECT puan FROM sorular WHERE ID = $value");
while($row = mysql_fetch_object($result) {
echo $value . ' = ' . $row->puan . ' | ';
}
}

Related

explode/implode from database php

I'm want string out of the column data.
But it failed.
<?php
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
$select_db = mysql_select_db("my_db", $conn) or die(mysql_error());
$select_tbl = mysql_query("SELECT * FROM log", $conn);
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (!isset($i[1])) {
for ($j = 0; $j <= 200; $j++) {
$i[$j] = null;
}
}
$name = $i[0];
$mama = $i[1];
$no = $i[2];
$a = $i[3];
$b = $i[4];
echo $name . "</br>";
echo $mama . $no . $a . $b . "</br>";
}
while ($data = mysql_fetch_object($select_tbl)) {
echo $data->data . "<br>";
}
?>
But i want output =
bus
car
bike
aabus
car
bike
aabus
car
bike
aabus
ddd
ee
And i not
Notice: Undefined offset: 3 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 21
Notice: Undefined offset: 4 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 22
Thank You.
You should just do what you want to do.
You want to connect to database then do it:
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
I suggest you to use mysqli library instead of mysql (mysql is deprecated in new php versions and totally removed in php7)
$conn = mysqli_connect("localhost", "nantawat", "12345678", "my_db") or die(mysql_error());
You want to query on log table, then do it:
$select_tbl = mysqli_query($conn, "SELECT * FROM log");
You want to fetch info from your result, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
echo $row['data'];
}
You want to explode data, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
$data = explode(',', $row['data']);
foreach ($data as $d) {
if ($d !== '') { // because before first comma or after last can be empty
echo $d . PHP_EOL;
}
}
}
If you want to save database result in variables:
If you are getting only one row of database, you can save them in variables directly:
$id_user = '';
$id_doc = '';
$date = '';
$data = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
}
And if you have multiple rows of database you need to save them all in a total array:
$array = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$data = array();
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
$array[] = array(
'id_user' => $id_user,
'id_doc' => $id_doc,
'date' => $date,
'data' => data,
);
}
And finally use this to see what structure your final array has:
echo '<pre>';
pront_r($array);
echo '</pre>';
First off it is not wise to store comma seperated values in a single cell and you are using deprecated mysql_ functions. I think your solution can be found in using a foreach instead of the isset part:
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
foreach ($i as $q){
echo $q . '<br/>';
}
}
If you still want to access your variables $name, $mama, $no and $ab, you can use isset for those specifically.
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (isset($i[0])){
$name = $i[0];
echo $name . '<br>'; //only echo if it exists
}
if (isset($i[1])){
$mama= $i[1];
echo $mama. '<br>'; //only echo if it exists
}
//try it yourself for $no and $ab
}
Try:
while ($row = mysqli_fetch_array($select_tbl)) {
extract($row);
/* Using extract method can get the array key value as variable
Below variables are available
$id_user;
$id_doc;
$date;
$data; */
}

Data in nested foreach loops used in update query

This is my code:
session_start();
/* loops through each row in the global $_SESSION variable which
contains the array and uses the $value to GET the data in the text
boxes and output them */
// studevent_result =
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
echo $studResult;
echo "<br>";
}
// result_postion =
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition = $_GET[$value];
echo $studPosition;
echo "<br>";
}
echo "<br>";
// stud_id =
foreach ($_SESSION['arrayId'] as $value) {
echo $value;
echo "<br>";
}
// UPDATE query, this will update the studevent_result and result_position
// column in the database for the specific stud_id.
$updateQuery = "
UPDATE result
SET studevent_result = '00:20:33',
result_position = '6'
WHERE result.stud_id = '12'
";
$updateRow = mysqli_query($conn, $updateQuery);
I use $_SESSION variables which all store an array. I extract the results of these arrays using foreach loops.
In $updateQuery, I want to make studevent_result = to the results of my first foreach loop above, result_position = to the results of the second foreach loop above and the result.stud_id = to the results of the third foreach loop above.
After me editing the code my code now looks like this:
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
foreach ($_SESSION['arrayNamePosition'] as $data) {
$studPosition = $_GET[$data];
foreach ($_SESSION['arrayId'] as $idValue) {
echo $idValue;
$updateQuery = "
UPDATE result
SET studevent_result = '$studResult',
result_position = '$studPosition'
WHERE result.stud_id = '$idValue'
";
$updateRow = mysqli_query($conn, $updateQuery);
}
}
}
I nested the foreach loops. But the problem now is that for the last foreach loop in the nested loops, $idValue in the query only uses the last element in the array $_SESSION['arrayId']. How can I fix this to loop throught the whole array, so that the query uses all the values in the array?
Thanks in advance.
If I understood your issue this should help you
session_start();
$i = 0;
$studResult = array();
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult[$i] = $_GET[$value];
$i++;
}
$studPosition= array();
$i=0;
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition[$i] = $_GET[$value];
$i++;
}
$stud_id = array(); $i=0;
foreach ($_SESSION['arrayId'] as $value) {
$stud_id[$i] = $value; $i++;
}
for($j =0; $j<$i; $j++){
$updateQuery = "
UPDATE result
SET studevent_result = '$studResult[$j]',
result_position = '$studPosition[$j]'
WHERE result.stud_id = '$stud_id[$j]'
";
$updateRow = mysqli_query($conn, $updateQuery);
}
Hope it will be helpful. Happy coding :)

getting duplicated results from nested foreach loop

I'm trying to get the following output from mysql for Google Line Chart API:
[["product","diameter","width"],["Product 1","2","4"],["Product 2","4","8"]]
I have set up several input checkboxes to send field names (e.g width,diameter) to the database via $_POST["info"] and retrieve the values from those fields. Here's the part that generates the data from mysql:
$result = $users->fetchAll();
$comma = "";
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
foreach($_POST["info"] as $p)
{
$d .= $comma.$r[$p]; // trying to get "$r["width"],$r["diameter"]"
}
$comma = ",";
$data[$i] = array($r["name"], $d);
$i++;
}
echo json_encode($data);
My desired output should be like this:
[["product","diameter","width"],["Product 1","2","4"],["Product 2","4","8"]]
But that code is generating duplicated results like this
[["product","diameter","width"],["Product 1","24"],["Product 2","24,4,8"]]
I guess I shouldn't be using the nested foreach to loop over $_POST. Can anyone tell me how to fix that?
Full PHP Code:
$info = $_POST["info"]; // It contains an array with values like width,diameter,thickness etc...
$comma = "";
foreach($info as $in)
{
$field .= "".$comma."b.".$in."";
$comma = ",";
}
$sql = "
SELECT {$field},a.user_id,a.name
FROM `product_detail` a INNER JOIN
`attr` b ON a.model = b.model
WHERE a.user_id = ?
GROUP BY a.model
";
$users = $dbh->prepare($sql);
$users->bindValue(1, $_SESSION["user_id"]);
$users->execute();
$result = $users->fetchAll();
$comma = "";
$data="";
$i = 1;
$data[0] = array_merge(array(product),$info);
foreach ($result as $r)
{
foreach($_POST["info"] as $p)
{
$d .= $comma.$r[$p];
}
$comma = ",";
$data[$i] = array($r["name"], $d);
$i++;
}
echo json_encode($data);
$_POST["info"] Content:
Array
(
[0] => diameter
[1] => width
)
try it like this:
$result = $users->fetchAll();
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
$d[]=$r["name"];
foreach($_POST["info"] as $p)
{
$d[]= $r[$p];
}
$data[$i] = $d;
$d=array(); //set $d to empty not to get duplicate results
$i++;
}
echo json_encode($data);
The end result you are looking for, is valid JSON. You should not try to manually generate that.
Instead you should make an array of arrays in php and use json_encode($array) to get the result you are looking for.
Also note that by injecting your POST variables directly in your query, you are vulnerable to sql injection. When accepting fields, you should check them against a white-list of allowed values.
Try the below solution:
$result = $users->fetchAll();
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
$d = array();
foreach($_POST["info"] as $p)
{
$d[] = $r[$p]; // trying to get "$r["width"],$r["diameter"]"
}
$data[$i] = array($r["name"]) +$d;
$i++;
}
echo json_encode($data);

Store data into array variable php

If i echo inside the while loop i get 4,2 values and if i echo outside the while loop then i only get 2. I want to get the data from $row into the values array. is something missing in this code?
$query = oci_parse($con, "SELECT count(*) FROM Counter GROUP BY Blog_name");
oci_execute($query);
while($row = oci_fetch_array($query))
{
$s = $row[0].',';
$values = explode(',', $s);
echo $values[0]; // 4
echo $values[1]; // 2
}
echo $values[0]; // 2
echo $values[1]; // 2
Try this,
$Values = array();
while($row = oci_fetch_array($query))
{
$Values[] = $row[0];
}
echo $Values[0];
First, $values as you're using it is just a string, and is not an array.
Try adding before the while loop.
$values = array();
Second, there's really no need to use explode here, it's an unnecessary step. If you only want the first column in the row, you can simply add that column to $values. (Currently you are overwriting the contents of $values at each iteration of the loop because you are missing the [].)
$values[] = $row[0];
If you're trying to put ALL of the columns in each row into values, try:
$values[] = $row;
If you're trying to individually put the contents of each column into it's own index in $values, try:
while($row = oci_fetch_array($query))
{
foreach($row as $column)
{
$values[] = $column;
}
}
Do like this:
$s = array();
while($row = oci_fetch_array($query)) {
$s[] = $row[0];
}
echo $s[0];
print_r($s);
$query = oci_parse($con, "SELECT count(*) FROM Counter GROUP BY Blog_name");
oci_execute($query);
$values = array();
while($row = oci_fetch_array($query))
{
$values[] = $row[0];
}
print_r($values);

Add string to all looped items except the last one

I'm looping through some mysql results and need to add <span id=bottom></span> to each of them except the last row. What's the easiest way of doing this?
Will I have to count rows and then use a counter and an if/else statement? Or is there an easier method?
Try something like this:
$result = mysql_query($sql);
$list = array();
while($row = mysql_fetch_assoc($result))
{
$list[] = $row;
}
$lastItem = array_pop($list);
foreach($list as $item) {
echo sprintf('<span id="bottom">%s</span>', $item['value']);
}
// do something with the last item..
Not very short, but that would do the trick. Alternatively you could do what you suggested:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
for($i = 0; $i < $num-1; $i++) {
$element = mysql_fetch_assoc($result);
// echo here..
}
$item = mysql_fetch_assoc($result); // fetch last item..
Best wishes,
Fabian
I'm not a PHP expert, but can you put each row in an array? That way to know the length and you can loop through the array.
$result = mysql_query($sql);
$list = array();
while($row = mysql_fetch_assoc($result))
$list[] = $row;
foreach(array_slice($list, 0, -1) as $item) {
echo sprintf('<span id="bottom">%s</span>', $item['value']);
}
// do something with the last item..
You can avoid copying all the data before processing it if you fetch a record in advance before printing it (or the other way round: process the previously fetched record)
foreach( $pdo->query('SELECT x FROM foo') as $r) {
if ( isset($row) ) {
echo '<span>', $row['x'], '</span>';
}
$row = $r;
}
if ( isset($row) ) {
echo $row['x'];
}

Categories