I have a table which holds truck info . I have another table which holds driver info (name and truck id there two of them in each trip) . I make a daily report from the first table regarding it's current status and I want to have a cell which holds the two current drivers. When I do join on the tables I get two rows from each truck and the only difference is the name of the driver.
Is there a way to produce a single row (either PHP or SQL query) ?
to get an idea my current result is this :
Truck:DRIVER1:Date:Destination:Cargo:Remarks
Truck:DRIVER2:Date:Destination:Cargo:Remarks
And I want to get something like this :
Truck:DRIVER1 DRIVER2:Date:Destination:Cargo:Remarks
is that even possible ? I'm fairly new to this
Say for example you have stored first fetched string in $str1 and second in the second variable $str2.
You can now just use ltrim() and rtrim() functions as
<?php
$str1 = 'Truck:DRIVER1:Date:Destination:Cargo:Remarks';
$str2 = 'Truck:DRIVER2:Date:Destination:Cargo:Remarks';
$result = ltrim($str2,'Truck:');
$result = rtrim($result,':Date:Destination:Cargo:Remarks');
?>
After this you get the value of $result as DRIVER2
And then you can just concatenate the result into string one as
$str1 = 'Truck:DRIVER1 '.$result.':Date:Destination:Cargo:Remarks';
And when you echo the $str you will get the desired output
Output
Truck:DRIVER1 DRIVER2:Date:Destination:Cargo:Remarks
Related
I have an array in php containing strings, which I want to use in a query with Red Bean MySQL in the following manner:
$someString = '\'abc\',\'def\',\'ghi\'';
R::getAll("select * from table where name not in (:list)", array(':list'=> $someString));
The problem is that the list is not being evaluated correctly no matter how I set the values in the array string, and the names abc, def, ghi are returned in the result. I've tried the following:
$someString = '\'abc\',\'def\',\'ghi\''
$someString = 'abc\',\'def\',\'ghi'
$someString = 'abc,def,ghi'
running the query in the SQL server manually works and I don't get those values returned, but running it within the php code with redbean is not working, and it seems that the list is not being interpreted correctly syntax-wise.
Can anyone shed some light on the matter?
Thanks to RyanVincent's comment I managed to solve the issue using positional parameters in the query, or more specifically, the R::genSlots function.
replaced the following:
$someString = '\'abc\',\'def\',\'ghi\'';
R::getAll("select * from table where name not in (:list)", array(':list'=> $someString));
with:
$someArray = array('abc', 'def', 'ghi');
R::getAll("select * from table where name not in (". R::genSlots($someArray) .")", $someArray);
This creates a $someArray length positions for parameters in the query, which are then filled with the values in the second parameter passed to the getAll function.
Notice that in this case I used a set content array (3 variables) but it will work dynamically with any length array you will use.
Furthermore, this can also work for multiple positions in the query, for example:
$surnameArray = array('smith');
$arr1 = array('john', 'pete');
$arr2 = array('lucy', 'debra');
$mergedVarsArray = array_merge($surnameArray,$arr1);
$mergedVarsArray = array_merge($mergedVarsArray,$arr2);
R::getAll("select * from table where surname != ? and name in (." R::genSlots($arr1).") and name not in (". R::genSlots($arr2) .")", $mergedVarsArray);
This code will effectively be translated to:
select * from table where surname != 'smith' and name in ('john','pete') and name not in ('lucy', 'debra')
Each '?' placed in the query (or generated dynamically by genSlots() ) will be replaced by the correlating positioned item in the array passed as parameter to the query.
Hope this clarifies the usage to some people as I had no idea how to do this prior to the help I got here.
I'm creating a simple lottery script.
The idea is that in one lottery there could be a few winners and I'm having troubles with checking if a new winner is a person who already won in this lottery.
I store this kind of data in DB.
list [longtext] - column with a list of contestants (separated with spaces or comas)
winner [longtext] - column with a list of winners in this lottery (separated with spaces)
My loop:
//$won_this is person who won in this round
$old_winners = $draw[winner];
$czy = strpos($old_winners, "$won_this");
while($czy == FALSE)
{
$add_winner = $won_this;
}
$sql = "update `draws` set `winner`= concat(winner, ' $add_winner') where code='$draw['number']'";
mysql_query($sql) or die(mysql_error());
My loop doesn't work. It will loop forever or not at all. I have no idea how to write this.
How can I create a loop that runs when a winner is duplicated and works until the new winner is found?
The first thing I would do is convert the old winners into an array:
$winners = explode(' ', $draw['winner']);
Then I would add the new winner to the array:
$winners[] = $won_this;
And finally I would call array_unique on the array to ensure uniqueness and then convert the array back into a string to be inserted into the database:
$winners_string = implode(' ', array_unique($winners));
$stmt = $connection->prepare("update `draws` set `winner`= ? where code = ?");
// Use bing_param('si'...) if $draw['number'] is an integer, not a string
$stmt->bind_param('ss', $winners_string, $draw['number']);
$stmt->execute();
Although ideally, and as mentioned in the comments to your question, there are better ways to store the data, e.g. have a new table with a draw_number column and a winner column and simply add a new row for each winner.
$czy is always false so nothing will happen in this script. It is always false because you are using the wrong syntax to search the array. Change your solution for checking your array Michael example is correct. Try it
I have been trying to get data from exploded values, but I am failing miserably and I am completely clueless despite all the researching I've been doing.
This is how the code looks like:
$array = explode(",", $hos['prop_owner']);
list($a) = $array;
$gu = $db->prepare("SELECT * FROM users WHERE user_id = :id");
$gu->execute(array(':id' => $a));
$dau = $gu->fetch();
echo $hos['prop_name']."<br><small>";
if(end($array)){
echo "<a href='/user/view/".$dau['user_id']."' style='color:#".$dau['user_colour']."'>".$dau['user_name']."</a></small><br>";
} else {
echo "<a href='/user/view/".$dau['user_id']."' style='color:#".$dau['user_colour']."'>".$dau['user_name']."</a>,";
}
Currently, the database field $hos['prop_owner'] contains the values "2,20" which are IDs of users (this field can potentially contain more IDs in the future). What I want to do is get all the user data from the exploded values, in this case 2 and 20, and then echo the information out in order as well.
Re-explanation:
I have a field in my database called prop_owner which is supposed to contain an unlimited number of user IDs, seperated by comma. Format: 1,2,3,4.
I want to take the value from this field, then somehow separate the user IDs and separately retrieve the usernames and echo them out.
Example result: Darren, Eva, Miles, Lisbeth
I hope I explained myself good enough to understand where I am trying to go with this.
Thanks in advance!
First of all the query will be like
SELECT * FROM users WHERE user_id in (2,20)
You need the data of both the users so the query will return all the data of all the ids that are being passed here..
You can directly pass here but you need to take care of security... or may be you can check how to pass values securely in such queries ...
I am looking to take the ID that auto increments already from the latest row in a table and increment it by one and append it on to a returned result from that same table. So if the row id is 5 and the tabledata result is product5, I need it changed to product6 in the php result. So when the data is resubmitted it is in-line with the new row ID.
EDIT:
I need it displayed and incremented before the sql insert because it's also emailed on data submit for ordering. The database insert is just to retain the order record.
Current code display results:
$conn=mysql_connect(" "," "," ");
mysql_select_db("database",$conn);
$sql="SELECT * FROM table WHERE ID=(SELECT max(ID) FROM table)";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_array($rs);
echo '<table>
<tr>
<td>Data: '.$result["tabledata"].'</td>
</tr>
</table>';
?>
What if you modify the query to select value after incrementing it. i.e.
SELECT ID+1 AS ID, /*all other fields of the table */ FROM table WHERE ID=(SELECT max(ID) FROM table)
So if I understand, you have two fields, not one:
id tabledata
1 PO-01
5 product5
is a Purchase order field so it stays in line with the previous just one number different (Example PO-01 to PO-02)
First thing that comes to mind is not to write that number in two places anyway. You could have
id tabledata
1 PO-%02d
5 product%d
and then wherever you had the row data, you could use
sprintf($row['tabledata'], $row['id'])
to get the "human readable" version of tabledata. Then to get the "next" ID you could just do
sprintf($row['tabledata'], $row['id'] + 1)
Otherwise, you need to extract the number from the text field. This requires that you know in advance its format (e.g. is it %d or %02d or...?).
If you know it is just the number, with variable length, as in your first example (product5 to product6), you do
$table['tabledata'] = preg_replace('#\\d+$#', $table['id'] + 1);
The above will replace the last sequence of numeric digits (here, 5; it could be 1701 for example) with 6. Or you can capture the number with preg_match and much the same expression, only in parentheses, increment it, and store it back.
If it is a fixed-length sequence of numbers as in your second example (PO-01 to PO-02), you just use substr:
$size = 2; // Two-digit number
$num = substr($table['tabledata'], -$size);
$prd = substr($table['tabledata'], 0, -$size);
$table['tabledata'] = $prd . sprintf("%0{$size}d", $num + 1);
An even more complicated solution would be to merge the two versions into a "decoding" function that would count leading zeroes and digit lengths and use this to determine the format being used. This however would have problems in some cases (e.g. maybe the next number out from AB-99 is not AB-100 but AC-00 or AC-01), so all in all I think this is best left to someone with the knowledge of the specific domain.
I have been working on this for a while now, I know it's simpler than what I am making it, but I just can't get it. I have some code where I am trying to query an enum either 1 or 0 from my table so this is exactly what I have to do this.
$username = 'test'
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='.$username.'");
Now I have all the connection stuff down I think, I get no errors there, but when I print this thing out in my echo I get this,
Heres my echo:
echo 'Hello, '.$username.', you Result is: '.$passResult.'!';
What I want to get is:
Hello, test, your Result is: 1
or
Hello, test, your Result is: 0
Now what I get is:
Hello, test, your Result is: Resource id #6
Now no matter what I do I get the same thing, I have no idea what I'm doing wrong here guys if someone could point this out that would be awesome. What this enum is being use essentially for a boolean just to see if the user has personally set a password not the computer generated version.
mysql_query returns a result resource, essentially a pointer to the memory where the results are buffered. That result set can contain many rows, as you can select many rows, so you need to fetch the row(s) you want then the column(s) you want from those rows.
/* execute the query and get a result resource back */
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='" . mysql_real_escape_string($username) . "'");
/* retrieve the first row from $passResult */
$row = mysql_fetch_assoc($passResult);
/* assign the usrSetPass column's value from that row to $passed */
$passed = $row['usrSetPass'];
Also, your query is wrong. You enclosed it in double quotes, so you're not actually breaking out of the string and concatenating $username when you use the single quotes and dots inside. I've corrected it above.
mysql_query doesn't return a value, it returns a resource (see here in the manual).
The returned result resource should be passed to another function for dealing with result tables (like mysql_fetch_array() or mysql_fetch_assoc()), to access the returned data.
Example based on your initial code:
$username = 'test';
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='".$username."'");
while ($row = mysql_fetch_assoc($passResult)) {
echo $row['usrSetPass'];
}