PHP & MySQL - Loop query if value is not null [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I currently have a database table setup like so:
| id | thing_id | value
The "thing_id" relates to a unique ID within the same table.
I'm trying to create a function (in PHP) that will run a query against the MySQL database, dump that information into an array, and if "thing_id" is NOT NULL it will loop back and run the query again, and add the information on to the existing array. This will continue until the "thing_id" is NULL.
How can I go about doing this? Btw, I'm designing this on top of WordPress.
The following below works, but I feel like there is some better way to do this. How can I simplify this and make it not hog resources? Here is what I have:
$related_thingsSql = "
SELECT $thingsDB.value, $thingsDB.thing_id, $thingsDB.id
FROM $thingsDB
WHERE $thingsDB.id = '$related_thing_id'
";
$related_things = $wpdb->get_results( "$related_thingsSql" );
foreach ($related_things as $related_thing) {
$related_thing_name[] = $related_thing->value;
$related_thing_id2[] = $related_thing->id;
$related_thing_id = $related_thing->thing_id;
}
while ($related_thing_id != NULL) {
$related_thingsSql2 = "
SELECT $thingsDB.value, $thingsDB.thing_id, $thingsDB.id
FROM $thingsDB
WHERE $thingsDB.id = '$related_thing_id'
";
$related_things = $wpdb->get_results( "$related_thingsSql2" );
foreach ($related_things as $related_thing) {
array_unshift($related_thing_name, $related_thing->value);
array_unshift($related_thing_id2, $related_thing->id);
$related_thing_id = $related_thing->thing_id;
if (empty($related_thing->thing_id)) {
$related_thing_id = NULL;
}
}
}
$related_things_length = count($related_thing_name);
for ($x = 0; $x < $related_things_length; $x++) {
echo ' > ' . $related_thing_name[$x] . '';
}

I figured out a way that works. I feel like this way is really sloppy, but it works. If anyone has any suggestions on how to improve this, feel free.
$related_thingsSql = "
SELECT $thingsDB.value, $thingsDB.thing_id, $thingsDB.id
FROM $thingsDB
WHERE $thingsDB.id = '$related_thing_id'
";
$related_things = $wpdb->get_results( "$related_thingsSql" );
foreach ($related_things as $related_thing) {
$related_thing_name[] = $related_thing->value;
$related_thing_id2[] = $related_thing->id;
$related_thing_id = $related_thing->thing_id;
}
while ($related_thing_id != NULL) {
$related_thingsSql2 = "
SELECT $thingsDB.value, $thingsDB.thing_id, $thingsDB.id
FROM $thingsDB
WHERE $thingsDB.id = '$related_thing_id'
";
$related_things = $wpdb->get_results( "$related_thingsSql2" );
foreach ($related_things as $related_thing) {
array_unshift($related_thing_name, $related_thing->value);
array_unshift($related_thing_id2, $related_thing->id);
$related_thing_id = $related_thing->thing_id;
if (empty($related_thing->thing_id)) {
$related_thing_id = NULL;
}
}
}
$related_things_length = count($related_thing_name);
for ($x = 0; $x < $related_things_length; $x++) {
echo ' > ' . $related_thing_name[$x] . '';
}

Related

Mysql search - in which don't have dots [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to search MySQL table and get in result in which don't have . (dot). example is below
example1.com
example2.com
example3
example4 com
So i want return, example 3 and 4. So basically i want row which don't have . (dot).
You can just use NOT LIKE:
SELECT column
FROM tablename
WHERE column NOT LIKE '%.%'
You can do that #fthiella suggested, or you can filter your search results in this was, using the stristr PHP function:
<?php
$searchQuery = 'example';
$sql = 'SELECT * FROM yourTable WHERE domain LIKE "%' . mysql_real_escape_string($searchQuery) . '%"';
$query = mysql_query($query);
$total = mysql_num_rows($query);
if($total) {
$data = array();
while($row = mysql_fetch_array($query)) {
if(stristr($row['domain'], '.') !== false) {
$data[] = $row['domain'];
}
}
die('<pre>' . print_r($data, true) . '</pre>');
} else {
die('Nothing was found.');
}
Note that I don't know your database table structure, so this is a psuedo-example.

how to create a variable using an array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
this is the code
$get_favory = mysql_query("SELECT * FROM favory WHERE user1='$username'");
$values = "";
while($fav = mysql_fetch_assoc($get_favory)) {
$user2 = $fav['user2'];
$values = " OR added_by='".$user2."'";
}
echo $values;
the values variable must be like this : OR added_by='zac' OR added_by='john' OR added_by='emily'
but i get this result : OR added_by='zac'
what i have to do?
Why your code is not working
You're overwriting the variable every time instead of appending the new value.
Solution
Replace
$values = " OR added_by='".$user2."'";
With
$values .= " OR added_by='".$user2."'";
Don't use mysql_ extension
mysql_ extension is deprecated. You should use mysqli_ instead.
Your code should be:
$connect = mysqli_connect(host,username,password,db_name);
$get_favory = mysqli_query($connect,"SELECT * FROM favory WHERE user1='$username'");
$values = "";
while($fav = mysqli_fetch_assoc($get_favory)) {
$user2 = $fav['user2'];
$values .= " OR added_by='".$user2."'";
}
echo $values;
Might be simpler using the IN clause:
// you only need user2
$get_favory = mysql_query("SELECT user2 FROM favory WHERE user1='$username'");
while($fav = mysql_fetch_assoc($get_favory)) {
$user2[] = $fav['user2'];
}
$values = "'" . implode("','", $user2) . "'";
echo "SELECT * FROM table WHERE added_by IN ($values)";
You should move to PDO or at a minimum the MySQLi extension.

Get a length of a php's result [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I don't know php at all so sorry for a simple question - I've got the project started by another person so now I'm trying to finish it.
The problem is - I'm making an android app for which I can't make a change without changing a php and this language I don't know.
here's this part :
function getPlaces(){
$result = array();
$sql = "SELECT id, name, short_description, photo_list, selected, recommended, isTOP FROM place
WHERE id IN(SELECT id_place FROM rubric_place WHERE id_rubric IN(SELECT id FROM rubric WHERE name = '".$_REQUEST["rubric"]."')) ORDER BY isTOP DESC";
getConnect();
$query = mysql_query($sql);
if(!$query){
error100();
}else {
$result['code'] = 200;
for ($i = 0; $i < mysql_num_rows($query); $i++) {
$row = mysql_fetch_assoc($query);
$result["places"][$i] = $row;
$sql = "SELECT * FROM rubric WHERE id IN(SELECT id_rubric FROM rubric_place WHERE id_place = ".$row[id].")";
$queryModule = mysql_query($sql);
if($queryModule){
for ($k = 0; $k < mysql_num_rows($queryModule); $k++) {
$rowModule = mysql_fetch_assoc($queryModule);
$result["places"][$i]["rubrics"][$k] = $rowModule;
}
}
$sql = "SELECT SUM(rating)/COUNT(rating) AS rating FROM comment WHERE id_place = ".$row[id];
$queryModule = mysql_query($sql);
if($queryModule){
$rowModule = mysql_fetch_assoc($queryModule);
$result["places"][$i]["rating"] = $rowModule[rating];
}
}
echo json_encode($result, JSON_UNESCAPED_UNICODE);
exit();
}
}
what I need is to make another function that returns in $result a value of "length" of places. I know I can find out length on the other end - in Android's app result, but this particular function will be changed so it will return by 20 results only so I need another function that returns length so plz help
To count the number of characters in a json you can do:
$string = json_encode($result, JSON_UNESCAPED_UNICODE);
$length = strlen($string);
You have to first put the json into a variable to count it, before outputting it.
To count the items in an array before you turn it into a json, you can do:
$length = count($array);

equivalent to foreach loop for just one row [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a PHP function that runs a SELECT Query in SQL:
if(!function_exists("SelectQuery")) {
function SelectQuery ($sql) {
global $conn;
$SelectQuery = mysql_query($sql,$conn);
return $NumRows=mysql_num_rows($SelectQuery);
$SelectQuery_Results=array();
while($SelectQuery_Row = mysql_fetch_array($SelectQuery)) {
$SelectQuery_Results[] = $SelectQuery_Row;
}
return $SelectQuery_Results;
}
}
then i am calling it here:
$sql="SELECT * from tickets where ticketnumber = '".$_GET["seq"]."' ";
$ticket = SelectQuery($sql);
foreach($ticket as $ticket2) {
}
rather than using a foreach loop what else could i use as my query will only be returning one row and i dont want to put my whole page within a loop
i tried just removing the foreach loop but that didnt work
Just access your value as $ticket[0].
A function cannot return two values for a single call. So, remove
return $NumRows=mysql_num_rows($SelectQuery);
You can check the array size for the number of rows in result.
If you want to echo out the result the following code will be ok!
if( sizeof($ticket) > 1 ){
foreach($ticket as $ticket2){
for($i=0; $i<sizeof($ticket2)/2; $i++)
echo "[" . $ticket2[$i] . "]";
echo "<br />";
}
}
$ticket is an integer see :
return $NumRows=mysql_num_rows($SelectQuery);
So you juste have to use $ticket.
If you want the row, remove this useless return in the SelectQuery function and use $ticket[0] for the first and only row.
Change the function with this :
function SelectQuery ($sql) {
global $conn;
$SelectQuery = mysql_query($sql,$conn);
$NumRows=mysql_num_rows($SelectQuery);
$SelectQuery_Results=array();
if ($numRows>1) {
while($SelectQuery_Row = mysql_fetch_array($SelectQuery)) {
$SelectQuery_Results[] = $SelectQuery_Row;
}
}
else $SelectQuery_Results = mysql_fetch_array($SelectQuery);
return $SelectQuery_Results;
}
Then use :
$sql="SELECT * from tickets where ticketnumber = '".$_GET["seq"]."' ";
$ticket = SelectQuery($sql);
if (is_array($ticket)) { foreach loop; }
else { use directly ticket['attribute'] }

Is this the correct way to query 2 mysql tables with php and a $_POST variable? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've been trying to figure out the best way to return an order from a database. I've come up with this, and it's working the way I want (I think) it gives me the results I'm looking for but I wanted to know if its correct or if there is a better way.
<?php
$conn = mysql_connect('', '', '');
if (!$conn)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbs, $conn);
$Order_ID = $_POST['Order_ID'];
//$Order_ID = '1001';
$queryOrderHead = "SELECT * FROM Orders WHERE Order_ID = '$Order_ID' ";
$queryOrderLines = "SELECT *
FROM Order_LineDetails
WHERE Order_LineDetails.Order_ID = '$Order_ID'
";
if ($queryRunHead = mysql_query($queryOrderHead)){
while ($info_HEAD = mysql_fetch_array($queryRunHead))
{
$OrderID_HEAD = $info_HEAD['Order_ID'];
$User_ID_HEAD = $info_HEAD['User_ID'];
$Customer_ID_HEAD = $info_HEAD['Customer_ID'];
echo $OrderID_HEAD.' '.$User_ID_HEAD.' '.$Customer_ID_HEAD.'<br>';
}
$queryRunLines = mysql_query($queryOrderLines);
while ($info = mysql_fetch_array($queryRunLines))
{
$OrderID = $info['Order_ID'];
$OrderLineID = $info['OrderLineItem_ID'];
echo $OrderID.' '.$OrderLineID.'<br>';
}
} else {
echo mysql_error();
}
mysql_close($conn);
?>
So what it does, is it uses the Order_ID val from the $_POST and runs the first query then on success it uses the same Order_ID and loops the second query and gets all the Order_LineDetails from a different table.
Other than the mysql_real_escape() tags....
Any pointers or ideas???
Any pointers or ideas???
There's nothing wrong with selecting the order first, then its items. However, you'd benefit from organizing the data into an array structure as well as following better naming conventions (both for variables and database schema):
$orderId = $_POST['order_id'];
// order_id should be an INT, so no quotes.
// Also look into parameterized queries with PDO as the mysql_* functions are archaic!
$sqlOrder = "SELECT *
FROM orders
WHERE order_id = ".mysql_real_escape_string($orderId);
$order = array();
if ($resOrder = mysql_query($sqlOrder)) {
if ($rowOrder = mysql_fetch_array($resOrder)) {
$order = $rowOrder;
// echo $rowOrder['order_id'].' '.$rowOrder['user_id'].' '.$rowOrder['customer_id']."<br />\n";
$sqlOrderLines = "SELECT *
FROM order_lines
WHERE order_lines.order_id = ".mysql_real_escape_string($orderId);
if ($resOrderLines = mysql_query($sqlOrderLines)) {
$order['order_lines'] = array();
while ($rowOrderLines = mysql_fetch_array($resOrderLines)) {
$order['order_lines'][] = $rowOrderLines;
// echo $rowOrderLines['order_id'].' '.$rowOrderLines['order_line_id']."<br />\n";
}
}
} else {
echo 'Order not found'.
}
} else {
echo mysql_error();
}
// debug
print_r($order);

Categories