PHP - Explode It Inside A Query?
Here is my query
Code: [Select] SELECT id,username,star,color,actions from users WHERE actions >= 1 ORDER BY actions DESC actions field value is "213|1336456267" how can I use mysql to explode so it only reads the first literation of the exploded values, like 213? Is this why people always say you shouldn't store exploded variables? Theres gotta be a way tho right? in other words; is there a mysql function that exploded that actions variable in the query with a | to read only the "213" ? Similar TutorialsGood day pals, Heres the description... I've got a base of some common phrases..Everything is working fine but for the output. I am using the php code function to explode the sentences of a <textarea> The explode works and splits the sentence into fragments. But where I'm now hooked is getting the mysqli_fetch_array to display the associated fragment words and display them. Please kindly help check this code and suggest where I might be missing something. Code: [Select] <?php //session_start(); // Define database connection constants define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'moby_thesaurus'); $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); if (isset($_GET['submit'])) { $sentence=$_GET['sentence']; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Next Stage</title> </head> <body> <?php if (isset($_GET['submit'])) { $sentence = $_GET['sentence']; // break $sentence using the space character as the delimiter $words = explode(' ', $sentence); //tell the amount of words using the size of the array echo 'The sentence has ' . count($words) . ' words.<br />'; // loop through and print all the words for ($i = 0; $i < count($words); $i++) { echo "Piece $i = $words[$i] <br />"; //echo 'Word ' . $i . ' - ' . $words[$i] . '<br />'; } } ?> <table> <form name="sentences" method="get" action="next.php?sentence=<?php echo 'sentence'; ?>" > <tr> <td> <textarea name="sentence" id="elm1"><?php echo $sentence; ?></textarea> </td> </tr> <tr> <td> <input name="submit" type="submit" value="Word_Count" /> </td> </tr> </form> </table> SYNONYMN WORDS <table width='200' border='1'> <tr> <td>S/N</td> <td>SENTENCE_WORD</td> <td>SYNONYM</td> <td>SYNONYM_ID</td> </tr></br> <?php $sel="select * from synonyms where synonym ='$i'"; $data=mysqli_query($dbc,$sel); $num= mysqli_num_rows($data); $n=1; if (!$data) { die('<p>Error Retrieving<br/>'. 'Error: ' .mysqli_error($dbc) . '</p>'); } if ($datalist=mysqli_fetch_assoc($data)) { do{ ?> <tr> <td><?php echo $n; ?></td> <td><?php echo $words[$i]?></td> <td><?php echo $datalist["synonym"]?></td> <td><?php echo $datalist["synonym_id"]?></td> </tr> <?php $n++; } while ($datalist=mysqli_fetch_array($data)); echo("</table> There are $num instances of the word '$synonym_word' in the base.</p>"); } ?> </body> </html> If you observe well I am using mysql query: [code <?php $sel="select * from synonyms where synonym ='$i'"; ?> [/code] With the explode array variable $i. But nothing outputs to the browser. Please I need suggestions... If I explode a string well using a substring when I implode that substring is now missing. for example. Code: [Select] $exploded = explode("[MAC]",$data); $data = implode($exploded); Now [MAC] would be missing in the $data string. any way to get around this? Can you use php for loops INSIDE of a mySQL query? Something like this, where $i varies... Code: [Select] $sql = "UPDATE answers SET "; for ($i=0;$i<=$total;$i++) { echo "answerid$i=$newnum$i," } WHERE something=$something"; $result = mysql_query($sql, $connection); if (!$result) { die("Database query failed: " . mysql_error()); } else { } I am really just a beginner in PHP but I've got a task to create a simple hotel booking system by using PHP and MySQL. It works in several steps, described in separate .php files. All of them seem to work fine, except the last one. In this last file I want to add all the data into a MySQL database table. I would like to do this by creating a record for each date, a guest is spending in a hotel (so that when booking, another loop checks whether the room is not occupied yet for that date). I decided to use a for-loop for that, but it doesn't seem to be working (the records just don't get inserted into the table). I checked all the variables by echo-ing them and they are all right. I also tried the query without the loop and it works as well. So I guess there is some other problem. This particular .php file looks as follow: <?php session_start(); include('db_config.php'); $name=($_POST['name']); $telephone=addslashes($_POST['telephone']); $email=addslashes($_POST['email']); $code=md5($email.time()); $checkout_date=$_SESSION['checkout']; $checkin_unix=$_SESSION['checkin_unix']; $checkout_unix=$_SESSION['checkout_unix']; $roomtype=$_SESSION['roomtype']; $checkin_date=$_SESSION['checkin']; for ($stay_date=$checkin_unix; ; $stay_date=$stay_date+24*60*60) { if ($stay_date=$checkout_unix){ break; } mysql_query("INSERT INTO reservations VALUES( '', '$roomtype', 'pending', 'date ('d/m/Y', $stay_date)', '$stay_date', '$checkout_date', '$name', '$telephone', '$email', '$code' )"); } ?> I would appreciate any kind of help, any idea. This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=347585.0 I have a table called "playlists", and a table called "musics". In the musics table, there is a column playlist_id which references the playlist that each music is contained.
I'm using api calls to display information on the site with JavaScript, so I need to return a JSON.
I need the json with the following structu
[
Playlists: [
{
Name: "etc",
musics: [
{
name: "teste.mp3" }, { name: "test2.mp3" } ] }, ... ] ] And this is my code: $query = $con->prepare("SELECT * FROM playlists WHERE user_id = :id"); i want to explode a text field on the fly ? for example city,region.country and to turn it to city_id,region_id,country_id 1.textfield from autocomplete 2.get post variable 3.explode 4 get ids i played around with some ajax with php Code: [Select] <html> <body> <input name="searchField" id="searchField" type="text" value="<?php echo $_POST['searchField'];?>"/> <script type="text/javascript"> function Ajax(){ var xmlHttp; try{ xmlHttp=new XMLHttpRequest();// Firefox, Opera 8.0+, Safari }catch (e){ try{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer }catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch (e){ alert("No AJAX!?"); return false; } } } xmlHttp.onreadystatechange=function(){ document.getElementById('ReloadThis').innerHTML=xmlHttp.responseText; var t=setTimeout('Ajax()',1000); clearTimeout(t); } var searchfieldvalue=encodeURIComponent(document.getElementById("searchField").value) xmlHttp.open("GET","getid.php?searchField="+searchFieldvalue+"",true); xmlHttp.send(null); } window.onload=function(){ var t= setTimeout('Ajax()',1000); } </script> <?php /*explode searchField and generate ids $searchField=$_POST['searchField']; $p = explode(" , ", $searchField, 3); $cityname=mysql_real_escape_string($p['0']); $regionname=mysql_real_escape_string($p['1']); $countryname=mysql_real_escape_string($p['2']); */ ?> <div id="ReloadThis">Default text</div> </body> </html> //getid <?php $p=array(); $p = explode(" , ", $_GET['searchField'], 3); echo $cityname=$p['0']; echo $regionname=$p['1']; echo $countryname=$p['2']; echo'<input type="hidden" name="place" id="place" value="'.$cityname.'"/> <input type="hidden" name="region" id="region" value="'.$regionname.'"/> <input type="hidden" name="country" id="country" value="'.$countryname.'"/>'; here ill add function to get city_id() etc ?> Hi, I have an array for prices : forfait="158|Group Session,95|Group half session,45|Private Course,90|zumba course" which is used in a dropdown list where it shows as Group Session (158$) Group half session (95$) etc... The prices need to be used as an 'amount' field on the gift certificate as the descriptions must show as a 'label' on the gift certificate. So, I need to ' explode ' both the prices and the descriptions separately. I can 'explode' de prices using $tmp_forfait=explode("|", $value) and I get 158 95 45 and 90 But, how do I get the descriptions separately, without the prices meaning I need to 'explode' the digits and '|' ... Anyone can help me with that cope please? Thank you Hi all, I posted a similar question before and got some of the way but still need a little help. I have a product database with a description column where there are strings broken into lines. I need to find a way to explode() by line break. Currently explode("/n") doesn't work - it only returns one array item. Can anyone help me out? Thanks! Hello Ive got a text area and i want to seperate each link that is placed inside the text area,. Is there a way using php exlode or somthing to reconise that the link has finished? Each of the links in the text area are on a new line. Thanks in advance. This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=316454.0 The Script:
$desired_width = 110; if (isset($_POST['submit'])) { $j = 0; //Variable for indexing uploaded image for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array $target_path = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/uploads/"; //Declaring Path for uploaded images $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $new_image_name = md5(uniqid()) . "." . $ext[count($ext) - 1]; $target_path = $target_path . $new_image_name;//set the target path with a new name of image $j = $j + 1;//increment the number of uploaded images according to the files in array if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded. && in_array($file_extension, $validextensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>'; $tqs = "INSERT INTO images (`original_image_name`, `image_file`, `date_created`) VALUES ('" . $_FILES['file']['name'][$i] . "', '" . $new_image_name . "', now())"; $tqr = mysqli_query($dbc, $tqs); // Select the ID numbers of the last inserted images and store them inside an array. // Use the implode() function on the array to have a string of the ID numbers separated by commas. // Store the ID numbers in the "image_file_id" column of the "thread" table. $tqs = "SELECT `id` FROM `images` WHERE `image_file` IN ('$new_image_name')"; $tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc)); $fetch_array = array(); $row = mysqli_fetch_array($tqr); $fetch_array[] = $row['id']; /* * This prints e.g.: Array ( [0] => 542 ) Array ( [0] => 543 ) Array ( [0] => 544 ) */ print_r($fetch_array); // Goes over to create the thumbnail images. $src = $target_path; $dest = $_SERVER['DOCUMENT_ROOT'] . "/gallerysite/multiple_image_upload/thumbs/" . $new_image_name; make_thumb($src, $dest, $desired_width); } else {//if file was not moved. echo $j. ').<span id="error">please try again!.</span><br/><br/>'; } } else {//if file size and file type was incorrect. echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>'; } } }Hey, sorry that I am posting this darn image upload script again, I have this almost finished and I am not looking to ask more questions when it comes to this script specifically. With the script above I have that part where the script should store the ID numbers (the auto_increment column of the table) of the image files inside of one array and then the "implode()" function would get used on the array and then the ID numbers would get inserted into the "image_file_id" column of the "thread" table. As you can see at the above part the script prints the following: Array ( [0] => 542 ) Array ( [0] => 543 ) Array ( [0] => 544 )And I am looking to insert into the column of the table the following: 542, 543, 544I thought of re-writing the whole image upload script since this happens inside the for loop, though I thought maybe I could be having this done with the script as it is right now. Any suggestions on how to do this? I tried to do this: explode(" ",$cp['size'])[0] and it isn't working obviously. The reason I want it in one line is its in the middle of a big string and I'd like to keep all the code in one area. Is their a right way to do that other than setting it to a variable first? Ok so what I have is a list of 32,000 IDs in a separate file called 32kIDs.txt and it has a list of roughly 32,000 user IDs for facebook which look like 100000233850312;1521225383;100000282767638;1252335882;1804268242 They're all separated by a semi-colon. What I need this script to do is echo each and every ID on screen, echoing each ID on a new line. I have been using the explode function but having trouble with it since I'm very new to PHP and don't have much experience yet. Here is my current code: <?PHP $iFile = "32kIDs.txt"; $login = file($iFile, FILE_SKIP_EMPTY_LINES); if(!is_file($iFile)) echo "The 32k add list couldn't be found...".sleep(999999); foreach($login as $line_num => $line) { $login = explode(" ", htmlspecialchars(str_replace(";"," ",$line))); echo $login[0]."\n"; } sleep(20); ?> So I bet there are going to be things in there that I don't even need and thing's I'm missing, if anyone can help it would be much appreciated. And I'd like to keep the code short, I could just put in: echo $login[0]."\n"; echo $login[1]."\n"; echo $login[2]."\n"; echo $login[3]."\n"; all the way up to echo $login[32246]."\n"; but yeah I don't like the thought of a 32k+ line script. Anyways... Hi all! This is probably fairly simple for someone who is used to dealing with arrays. I have an array of data(Parsed from an XML document) containing a string I would like to further split into another array. The string is along the lines of: "<name>":<value>,"ID":20251,"ID2":2300,"ID3":2000 How can I split the above into: Array[<NAME>] => <VALUE> Notes: <name> changes often. depending on the query, it may have different <name> values. I have been trying to do it with preg_split and got to: Array ( => "<NAME>":<VALUE> [1] => "ID":20251) but I need to split it further at ":". I tried a foreach, but I failed miserably. Can anyone point me in the direction of better practice for arrays/preg_split? I have looked into the PHP documentation, but it is not enough for me. Thanks in advance how to take a word in php or explode based on luas Bangunan :xxx For example I have string $string =" Kondisi Properti : Bagus Dilengkapi Perabotan : Unfurnished Sertifikat : Lainnya Daya Listrik : 2200 Watt Kamar Tidur : 3/1 Kamar Mandi : 2/1 Luas Bangunan : 92 m² Luas Tanah : 126 m² Jumlah Lantai : - Kondisi Properti : Bagus Sekali Dilengkapi Perabotan : Unfurnished Sertifikat : SHM - Sertifikat Hak Milik Daya Listrik : 6600 Watt Saluran Telepon : 1 Garasi : 3 Kamar Tidur : 4/1 Kamar Mandi : 3/1 Luas Bangunan : 300 m² Luas Tanah : 228 m² Jumlah Lantai : 2.5 "; eg I want to take every "Luas bangunan: xxx" Thanks Lets say I have a URL of http://mydomain.com/somename/ I need a function to grab USERNAME However I need it to work if someone uses http://www.mydomain.com/USERNAME/ OR With or without the trailing / after USERNAME I can't see to figure anything out which accounts for the many different variables that a person could type it. And yet another way is that the URL could be http://www.mydomain.com/USERNAME/SOME-CAT/SOME-POST/ Thanks Hi, I have a database that is going to contain recepies and ingredients tables. The recipe table is going to store the ingredients like this: 1,5,6,8 This refers to the table ingredients id. I now want to explode these vaules and count them up so they can be outputted like this: sugar (2) honey(1) flour (3) I have no idea of how to count all of the exploded id's and ouput them like above With a database of synonyms, how do I compare a fragment of a texarea sentence split by the php explode function to return only five synonyms out of say 100 synonyms of the same word for each fragment. The Sql statement is queried to return 5 results Code: [Select] <?php if (isset($_GET['submit'])) { $sentence = $_GET['sentence']; // break $sentence using the space character as the delimiter $words = explode(' ', $sentence); //tell the amount of words using the size of the array echo 'The sentence has ' . count($words) . ' words.<br />'; // loop through and print all the words for ($i = 0; $i < count($words); $i++) { echo "Piece $i = $words[$i] <br />"; //echo 'Word ' . $i . ' - ' . $words[$i] . '<br />'; //$words=$_GET['words']; $sel="select * from synonyms where synonym LIKE '%$words[$i]%' limit 3"; $data=mysqli_query($dbc,$sel); $num= mysqli_num_rows($data); if (!$data) { die('<p>Error Retrieving<br/>'. 'Error: ' .mysql_error() . '</p>');} $datalist=mysqli_fetch_assoc($data); $synonym=$datalist['synonym']; ?> I intend to use a 2 texareas: 1. Code: [Select] <textarea name="split_sentence"><?php echo "sentence" ?></textarea> the 1st <texarea> has the original sentence to be split by the explode function. 2. Code: [Select] <textarea name="split_sentence2"><?php echo ("$words[$i] {{$synonym}}?></textarea> the second <texarea> should take the explode fragments compare it with the query above and return five synonyms per word on a SINGLE <textarea> tag. 3. Besides, I keep getting this offset error on the 2nd <texarea> refering to the $words[Si] array element in the 2nd <textarea> Below is the full code: Code: [Select] `<?php //session_start(); // Define database connection constants define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'moby_thesaurus'); $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>compare_words</title> </head> <body> <table><p> PLEASE ENTER INITIAL SENTENCE </p> <form name="sentences" method="get" action="" > <tr> <td> <textarea name="sentence" id="elm1"></textarea> </td> </tr> <tr> <td> <input name="submit" type="submit" value="Create_Spinable Content" /> </td> </tr> </form> </table> <?php if (isset($_GET['submit'])) { $sentence = $_GET['sentence']; // break $sentence using the space character as the delimiter $words = explode(' ', $sentence); //tell the amount of words using the size of the array echo 'The sentence has ' . count($words) . ' words.<br />'; // loop through and print all the words for ($i = 0; $i < count($words); $i++) { echo "Piece $i = $words[$i] <br />"; //echo 'Word ' . $i . ' - ' . $words[$i] . '<br />'; //$words=$_GET['words']; $sel="select * from synonyms where synonym LIKE '%$words[$i]%' limit 3"; $data=mysqli_query($dbc,$sel); $num= mysqli_num_rows($data); if (!$data) { die('<p>Error Retrieving<br/>'. 'Error: ' .mysql_error() . '</p>');} $datalist=mysqli_fetch_assoc($data); $synonym=$datalist['synonym']; ?> <table><p> SPINABLE CONTENT </p> <form name="sentences" method="get" action="" > <tr> <td> <?php if ($datalist=mysqli_fetch_array($data)) { do{ ?> <textarea cols="80" id="editor1" name="sentence" rows="10"><?php echo ("$words[$i] {{$synonym}}||{{$synonym}}||{{$synonym}}"); ?></textarea> <?php } while ($datalist=mysqli_fetch_array($data)); echo("</table> </p>"); } ?> <?php } } ?> </td> </tr> <tr> <td> <input name="submit" type="submit" value="Spin This Now" /> </td> </tr> </form> </table> </body> </html> Please any suggestions would be highly appreciated. Code: [Select] $newrating = round($imageinfo['rating'],2); this outputs: 4.49 in my db rating is 4.4884 all i need is the 4.... would i use some type of preg_replace or something just to grab the first 1 before the decimal? (all i need is the first number before the decimal) |