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'] }
Related
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 5 years ago.
Improve this question
I have a dynamic input form, I want to check if the record exists, if no then it can not insert data
my controller
$user = Master::where('id_a','=',$request->get('id_a'))->where('id_b','=',$request->get('id_b'))->get();
if($user->isEmpty()){
// insert
}else{
//message "cannot input"
}
if insert one data, success.. but if insert array in my controller not check..
why in input array data always insert???
This is pseudo for only check id_b
$data = [1,2,3,4];
$data_a = [1,2,3,4];
$masters = Master::whereIn('id_b', $data)->whereIn('id_a', $data_a)->get();
foreach($data as $key => $value) {
$isExisted = false;
foreach ($masters as $master) {
if ($master->id_b == $value[$key] && $master->id_a == $data_a[$key])
{
$isExisted = true;
break;
}
}
if ( ! $isExisted) {
$master = new Banner();
$master->value = your_data;
$master->save();
}
}
You could use exists()
if(Master::where('id_a','=',$request->get('id_a'))->where('id_b','=',$request->get('id_b'))->exists()) {
do something
}
Also I would suggest you reduce the amount of in-line stuff you're doing, instead something like this:
$id_a = $request->get('id_a');
$id_b = $request->get('id_b');
if(Master::where('id_a','=', $id_a)->where('id_b','=',$id_b)->exists()) {
do something
}
If I understand correctly, you want to insert a Master if a given id_a and id_b doesn't already exists for one Master
If so, you could actually use firstOrCreate :
Master::firstOrCreate(
['id_a' => $request->get('id_a'), 'id_b' => $request->get('id_b')],
['yourcolumntocreate' => columnvalue, ...]
)
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] . '';
}
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.
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 8 years ago.
Improve this question
I'm trying to use PHP as a way to process this in a webpage, my typical language is java so i am unfamiliar with how this would be done for product keys.
This is basically the process:
1. Generate random string with format XX-XXXX-XXXX-XXX a mix of numbers and letters.
2. Check if it already exists in an SQL database
3. If exists, generate another one and repeat?
So how would I do this using PHP?
Please explain what i would need to do and what is the best way of going about it.
Generate random string from following function.
<?php
function randomString() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
$array_lengths = array(2,4,4,3);
foreach($array_lengths as $v){
for ($i = 0; $i < $v; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
$pass[] = '-';
}
return rtrim(implode($pass),'-'); //turn the array into a string
}
echo randomString();
?>
SQL
Please create unique key field and use ON DUPLICATE KEY query for insert/ update data
DEMO
You can generates randomnumbers key using this way.
echo rk(2)."-".rk(4)."-".rk(4)."-".rk(3);
function rk($chars) {
$letters = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
return substr(str_shuffle($letters), 0, $chars);
}
Here's a process that could be of use!
<?php
/** The function below was taken from http://stackoverflow.com/questions/853813/how-to-create-a-random-string-using-php **/
function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'){
$str = '';
$count = strlen($charset);
while ($length--) {
$str .= $charset[mt_rand(0, $count-1)];
}
return $str;
}
/** The function that will do your work is: **/
function theProcess(){
/** Now to inefficiently concatenate your random string together. **/
$theString = randString(2)."-".randString(4)."-".randString(4)."-".randString(3);
echo $theString;
/** Proceed to query your database using MySQLi or PDO, with a query similar to: **/
/** Add your preliminary (connection) code here. **/
$sthandler = $dbhandler->prepare('SELECT 1 FROM products WHERE productKey = ?');
$sthandler->execute(array($theString));
/** Check whether a result is returned from MySQL. **/
if ($sthandler->rowCount() > 0) {
exit("IT EXISTS!");
} else {
theProcess();
}
}
/** Call the function the first time. **/
theProcess();
?>
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);