PHP - String Values Into Variables
Hi, I have a string with the value of { "success": true, "delivered": true, "contactDetailsRequired": false, "message": "Signed For by: D ANDERSON ", "signature": "https://webservices.thedx.co.uk/PodImage/ImageHandler.ashx?tn=906732192165", "date": "21-07-2020", "serviceLevelName": "Consigned", "time": "13:33:19", "trackedProductName": "DataExchange" } How do i go about placing the values into variables so for example: $success = "true"; $delivered = "true"; $message = "Signed for by: D ANDERSON"; etc.... My mind has gone blank and im having one of those days, any help would be greatly appreciated. Thanks Similar TutorialsI have a string that looks like /index.php?g1=111&g2=222&g3=333. How can I obtain the value of g1 (i.e. 111)? It does not represent the current state of the server thus I cannot just use $_GET. It also is not necessarily the first item. The script below appears to work, however, http://php.net/manua...n.parse-url.php states This function is intended specifically for the purpose of parsing URLs and not URIs. However, to comply with PHP's backwards compatibility requirements it makes an exception for the file:// scheme where triple slashes (file:///...) are allowed. For any other scheme this is invalid. It appears that my string is a URI and not a URL, but I might be wrong. How should this be accomplished <?php $str='/index.php?g1=111&g2=222&g3=333'; $array=parse_url($str); parse_str($array['query'],$get); echo("<p>{$get['g1']}</p>"); ?> hello, im wondering how to properly code the following. Code: [Select] $stdate = date( 'Ymd', strtotime($pdate) ); $sttime = date( 'His', strtotime($tstart1) ); $dtStart = ".$stdate.'T'.$sttime.'Z'"; echo "$dtStart"; i would like the echo to read 20110309T050000Z I have the following code which has deliimiters of |||| and I need to break it apart into three strings and have a variable assigned to each string. I've tried exploding it but won't dynamically increase the variable. I know at one point about a year ago I used something like $var.=$foo and the $var would increase $var1, $var2, etc... Here's the string I need to break.j (And the string will be different every time, and some will have 2 string delimited some will have 20, and some inbetween. The rich contemporary style of the "Theo" Counter Height Table combines faux marble and a warm finish to create dining room furniture that adds an exciting style to the decor of any home. The thick polyurethane coated faux marble table top perfectly accentuates the warm brown finish flowing over the straight-lined contemporary design of the apron and legs to help create an exceptional dining experience. With the beautiful stitching and button tufting details of the faux leather upholstered bar stools, the "Theo" Counter Height Table is a refreshing addition to any home.||||Table top made with polyurethane coated print marble. Aprons and legs made from select veneer and solids with a warm brown finish. Chair is upholstered in a brown PVC with accent top stitching. D158-233 bar stool dimension: 18"W x 21"D x 40"H.||||Click here for complete image download listing for series D158. In a perfect world it would be: Code: [Select] $desription1="The rich contemporary style of the "Theo" Counter Height Table combines faux marble and a warm finish to create dining room furniture that adds an exciting style to the decor of any home. The thick polyurethane coated faux marble table top perfectly accentuates the warm brown finish flowing over the straight-lined contemporary design of the apron and legs to help create an exceptional dining experience. With the beautiful stitching and button tufting details of the faux leather upholstered bar stools, the "Theo" Counter Height Table is a refreshing addition to any home."; $description2="Table top made with polyurethane coated print marble. Aprons and legs made from select veneer and solids with a warm brown finish. Chair is upholstered in a brown PVC with accent top stitching. D158-233 bar stool dimension: 18"W x 21"D x 40"H.": $description3="Click here for complete image download listing for series D158."; $id[] = 12345; $id[] = 12345; $id[] = 12345; $id[] = 12345; $id[] = 12345; how would I combine these into a string "12345,12345,12345,12345,12345" Hi I am trying to get all variables passed in a url string and wondered how would i do it? I dont know what they are yet and i need to set key as value. Any help? Pretty simple I would think but I'm unsure on the syntax. I have a variable, $ename. It's actually data from a form that I pass to said variable. What I want is to then in turn use this string in a mkdir() function. Something like Code: [Select] mkdir("dir/folder/$ename/"); Obviously that doesn't work. I'd imagine I have to use some sort of . syntax. I need to echo out some string variables in a form. I also want to add some validation for Name, email etc. I think I have the code right or close, but I can an error on the index.php page which is. "Fatal error: Call to undefined function form_row_class() in index.php on line 14" here is the code for the form <!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> <title>String Tester</title> <link rel="stylesheet" type="text/css" href="main.css"/> </head> <body> <div id="content"> <h1>String Tester</h1> <form action="submit.php" method="post"> <table> <tr class="<?php echo form_row_class("name") ?>" > <th><label for="first_name">Name</label></th> <td> <input name="first_name" id="first_name" type="text" value="<?php echo h($_POST['name']); ?>" /> <?php echo error_for('name') ?> </td> </tr> <tr class="<?php echo form_row_class("email") ?>"> <th><label for="email">Email Address</label></th> <td> <input name="email" id="email" type="text" value="<?php echo h($_POST['email']); ?>" /> <?php echo error_for('email') ?> </td> </tr> <tr> <th></th> <td><input type="submit" value="submit" /></td> </tr> </table> </form> <h2>Message:</h2> <?php echo "<table>"; echo "<tr><td>"; echo $name; echo "</td></tr>"; echo "<tr><td>"; echo $email; echo "</td></tr>"; echo "<tr><td>"; echo $phone; echo "</td></tr>"; echo "</table>"; ?> </div> </body> </html> and the submit portion <?php // If request is a form submission if($_SERVER['REQUEST_METHOD'] == 'POST'){ // Validation // Check first_name is non-blank if(0 === preg_match("/\S+/", $_POST['name'])){ $errors['name'] = "Please enter a name."; } // Check email is valid (enough) if(0 === preg_match("/.+@.+\..+/", $_POST['email'])){ $errors['email'] = "Please enter a valid email address."; } // validate a phone number if( !preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone) ) { echo 'Please enter a valid phone number'; } // If no validation errors if(0 === count($errors)){ // Sanitize first, last, and email $name = mysql_real_escape_string($_POST['name']); $email= mysql_real_escape_string($_POST['email']); $email= mysql_real_escape_string($_POST['phone']); } // Helpers function form_row_class($name){ global $errors; return $errors[$name] ? "form_error_row" : ""; } function error_for($name){ global $errors; if($errors[$name]){ return "<div class='form_error'>" . $errors[$name] . "</div>"; } function h($string){ return htmlspecialchars($string); } ?> probably something simple I am missing. Hi Guys and Girls, Long time lurker, first time poster! I am usually able to read through the forums and find and answer without having to start a new thread but I've tried my best to no avail. I am having trouble with the following code: $afname="Gareth"; $alname="B"; $awayoption.="<OPTION VALUE=\"".$afname." \"".$alname."\">".$afname." ".$alname; I would want that to produce the following: Code: [Select] <OPTION VALUE=Gareth B">Gareth B The actual result at the moment is: Code: [Select] <OPTION VALUE="Gareth "B">Gareth B It has an extra " in the middle. Any ides or help would be great! Cheers Hi I am adapting Jeffery Ways Mysql class to accept multiple where statements however I have got stuck on the final hurdle. It is when I try to do the bind_results() and I pass in the parameter types and the parameters. Here is that part of the code: if ($this->_where) $values = array_values($this->_where); $str = "'"; $str .= implode('\', \'', $values); $str .= "'"; // echo $str; $count = count($this->_where); foreach($this->_where as $key => $value){ $key = $value; } $user = 'matt25'; $pass = '6722853cacc4a9649dc75abc852f23c35b1f75cb'; $stmt->bind_param($this->_paramTypeList, $user, $pass); } It works how it is by setting the parameters as variables, but that obviously isn't practical. as you can see I also tried to make a string with the values from the array which brought up the error: Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of elements in type definition string doesn't match number of bind variables in C:\wamp\www\trick_tips\admin\includes\MysqlDb.php on line 260, the same as when I try to put the array into there. So I need some way of setting each value in the array as a variable to then put into the function, or another Idea that I have completely missed. Any help would be much appreciated. Cheers, Matt Hi all, I am having some trouble with a script.. all works fine except for the calculation part. It isn't adding up, but the reason for this is because when I echoed all the variable it seems that they are blank, the problem is I can't figure out why? <?php # you don't display errors on in-use scripts, do you? ini_set('display_errors',0); error_reporting(E_ALL|E_STRICT); class webPoll { # makes some things more readable later const POLL = true; const VOTES = false; # number of pixels for 1% on display bars public $scale = 2; public $question = ''; public $answers = array(); private $header = '<form class="webPoll" method="post" action="%src%"> <input type="hidden" name="QID" value="%qid%" /> <h4>%question%</h4> <br /> <ul>'; private $center = ''; private $footer = "\n</ul>%button%\n</form>\n"; private $button = '<p class="buttons"><button type="submit">Vote!</button></p>'; private $md5 = ''; /** * --- * Takes an array containing the question and list of answers as an * argument. Creates the HTML for either the poll or the results depending * on if the user has already voted */ public function __construct($params) { $this->question = array_shift($params); $this->answers = $params; $this->md5 = md5($this->question); $this->header = str_replace('%src%', $_SERVER['SCRIPT_NAME'], $this->header); $this->header = str_replace('%qid%', $this->md5, $this->header); $this->header = str_replace('%question%', $this->question, $this->header); # seperate cookie for each individual poll isset($_COOKIE[$this->md5]) ? $this->poll(self::VOTES) : $this->poll(self::POLL); } private function poll($show_poll) { $replace = $show_poll ? $this->button : ''; $this->footer = str_replace('%button%', $replace, $this->footer); # static function doesn't have access to instance variable if(!$show_poll) { $results = webPoll::getData($this->md5); $votes = array_sum($results); } for( $x=0; $x<count($this->answers); $x++ ) { $this->center .= $show_poll ? $this->pollLine($x) : $this->voteLine($this->answers[$x],$results[$x],$votes); } echo $this->header, $this->center, $this->footer; } private function pollLine($x) { isset($this->answers[$x+1]) ? $class = 'bordered' : $class = ''; return " <li class='$class'> <label class='poll_active'> <input type='radio' name='AID' value='$x' /> {$this->answers[$x]} </label> </li> "; } private function voteLine($answer,$result,$votes) { echo "Answer: $answer"; echo "<br />"; echo "Result: $result"; echo "<br />"; echo "Votes: $votes"; echo "<br />"; echo "<br />"; $result = isset($result) ? $result : 0; $percent = round(($result/$votes)*100); $width = $percent * $this->scale; return " <li> <div class='result' style='width:{$width}px;'> </div>{$percent}% <label class='poll_results'> $answer </label> </li> "; } // remainder of script here ?> The ones that are returning blank a $result and $votes $results should be the number of votes a specific option has received while $votes is the total number of votes in the whole poll. My database contains the following data... QID AID votes 685b9628ca340529fa54208c65721dd7 2 205 685b9628ca340529fa54208c65721dd7 0 5 685b9628ca340529fa54208c65721dd7 1 2 It's from the following tutorial - http://net.tutsplus.com/tutorials/ph...poll-with-php/ Can anyone advise me here? Many thanks, Greens85 I have an audit trail that record users ids and a copy of the sql string for any updates they make to my application. This is very easy for me to follow to find exactly where changes happened but do end users it is a bit of a challenge. Has anyone seen or made a script that can either compare two sql strings to see what fields have different values or a script that takes an SQL string and outputs its field names and values to an array that I can use for comparisons? Example being the look at a update made by user X, the database pulls the sql for that change then looks for the previous change up any user before (update sql should have a value for all fields) then compares to see what user X changed. If not im thinking of case statement to divide sql request between inserts and update then writing a script to split the strings based on where the commas were. Any thoughts? Code: [Select] $query = "SELECT content FROM license WHERE serial = '".$serial."'"; Hi, I currently have a string with some values in it: $a_random_string="some random text, goes here - $123<br>some more random text goes here - $53 (text 123 )<br>ANother line of text - $126"; Now I want to add all the values that have a '$' before the value eg; $123. So in this case I would end up with: 302 How would I do this? Thanks, mme $username = $_POST['uid']; $email = $_POST['mail']; $password = $_POST['pwd']; $passwordRepeat = $_POST['pwd-repeat']; $date = $_POST['date2']; $stream = $_POST['relationship']; $sql1 = "INSERT INTO users (uidUsers, emailUsers, pwdUsers, relationship) VALUES (?, ?, ?, ?);"; $sql2 = "INSERT INTO Family1 (username, application_filed, relationship) VALUES (?, ?, ?);"; $sql3 = "INSERT INTO Family2 (username, application_filed, relationship) VALUES (?, ?, ?);"; mysqli_query($sql1, $conn); mysqli_query($sql2, $conn); mysqli_query($sql3, $conn); $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql2)) { header("Location: ../signup.php?error=sqlerror"); exit(); } else { mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream); $result = mysqli_stmt_get_result($stmt); if ($row = mysqli_fetch_assoc($result)) ($username==$_SESSION['uid'] and $stream =='nursing'); mysqli_stmt_execute($stmt); } if (!mysqli_stmt_prepare($stmt, $sql3)) { header("Location: ../signup.php?error=sqlerror"); exit(); } else { mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream); $result = mysqli_stmt_get_result($stmt); if ($row = mysqli_fetch_assoc($result)) ($username==$_SESSION['uid'] and $stream =='doctoral'); mysqli_stmt_execute($stmt); } if (!mysqli_stmt_prepare($stmt, $sql1)) { header("Location: ../signup.php?error=sqlerror"); exit(); } if (!mysqli_stmt_prepare($stmt, $sql1)) { header("Location: ../signup.php?error=sqlerror"); exit(); } else { $hashedPwd = password_hash($password, PASSWORD_DEFAULT); mysqli_stmt_bind_param($stmt, "ssss", $username, $email, $hashedPwd, $stream); mysqli_stmt_execute($stmt); header("Location: ../signup.php?signup=success"); exit(); I was wondering if someone could point me in the right direction. I have this code. They idea I had behind it is to insert values into different tables depending on variables being passed. So when user fills out a form and selects $stream="nursing" I want results to go to table 'users' and 'Family1', but not 'Family2' table. and if user selects $stream='doctoral' results should go to table 'users' and 'Family2', and not go to 'Family1' But with my query I get results go to both table and also users table. And there is no restriction to what users selects, variable $stream being passed no matter what it is. Is this the wrong way to go here? Did I completely mess up the logic? I've googled a lot but still can't find much of a clue for how to do this (printing all environment variables in PHP that is). I know it has something to do with $_ENV and $_SERVER but... I would be thrilled for some guidance! Best regards, Rasekamon What would be the correct way to use returned sql results as variables. I have tried the way in my script, but Im unsure of how I can echo just one of the $nt variables further on in my script. $code = $_GET['postcode']; $shortcode = substr($code,0,2); $query =mysql_query ("SELECT email FROM treesurgeons WHERE postcode like '%" . $shortcode . "%' ORDER BY companyName LIMIT 3"); echo mysql_error(); echo "<p>The email addresses you have requested are;</p>"; while($nt=mysql_fetch_row($query)){echo "$nt[0],$nt[1],$nt[2]<br>";} echo "<p>please use $nt[2] if you ever want to contact me</p>"; //this line doesnt work for me ?></body></html> is there is a way to assign variables such as; $nt[0] = $firstemail $nt[1] = $secondemail $nt[2] = $thirdemail this way I could use each of my sql values, just as I would any other variable? As part of my User Profile, I have a series of open-ended questions that Members can answer, e.g... Quote 1.) Why did you start your own business? 2.) If you could offer one piece of advice to other entrepreneurs, what would it be? : 10.) How do you compete against large corporations? I was leaning towards creating a many-to-many relationship like this... member -||---------0<- answer ->0---------||- question From a database standpoint this works great, HOWEVER, I just realized a big problem... If run this query... Code: [Select] SELECT response FROM answer WHERE member_id = 1; ...then I would get TEN RECORDS back and I don't know of any way to maps those to the 10 Text Boxes on the "My Thoughts" page?! (It would be a real PITA to have to create 10 separate Prepared Queries in PHP - one for each Field - to fill out my page?!) So, is there a way to keep my table structure, but push the 10 records from above into 10 separate variables so I would have something like $response1, $response2,... $response10 ?? Thanks, Debbie I have a DB of data: article-id, section-id, subsection-id, article-text. When a row is fetched I am displaying article, section, subsection as <h3>, <h4>, <h5> and then text in a <p>. Before outputting the text I want to scan it for other articles, sections, or subsections it may reference then turn that reference into a hyperlink. I read the PHP documentation but I can't find anything that translates to the basic commands of instring, indexof, and left/mid/right. Example: 1. Article Name 100. Article 1, section 1 100.a article 1, section 1, subsection a Text blah blah blah 105.f blah blah blah
I want to find that 105.f and turn it into a link. All my articles, sections, and subsections are in the DB so I know I can use an array of the number values as my items to look for, but I can't figure out how to look. okay all i need is a way to make 4 <OPTION> values into a string which i can compare to a row in my db. This is my form. Code: [Select] <select name='n1'> <option value='0'>0</option> <option value='1'>1</option> <option value='2'>2</option> <option value='3'>3</option> <option value='4'>4</option> <option value='5'>5</option> <option value='6'>6</option> <option value='7'>7</option> <option value='8'>8</option> <option value='9'>9</option> </select> <select name='n2'> <option value='0'>0</option> <option value='1'>1</option> <option value='2'>2</option> <option value='3'>3</option> <option value='4'>4</option> <option value='5'>5</option> <option value='6'>6</option> <option value='7'>7</option> <option value='8'>8</option> <option value='9'>9</option> </select> <select name='n3'> <option value='0'>0</option> <option value='1'>1</option> <option value='2'>2</option> <option value='3'>3</option> <option value='4'>4</option> <option value='5'>5</option> <option value='6'>6</option> <option value='7'>7</option> <option value='8'>8</option> <option value='9'>9</option> </select> <select name='n4'> <option value='0'>0</option> <option value='1'>1</option> <option value='2'>2</option> <option value='3'>3</option> <option value='4'>4</option> <option value='5'>5</option> <option value='6'>6</option> <option value='7'>7</option> <option value='8'>8</option> <option value='9'>9</option> </select> here is the php code which i tried but doesnt seem to work. Code: [Select] $n1 = $_POST['n1']; $n2 = $_POST['n2']; $n3 = $_POST['n3']; $n4 = $_POST['n4']; $string = ("" . $n1 . "" . $n2 . "" . $n3 . "" . $n4 . ""); echoing $string does give to correct numbers.. but when i try and compare it to my database it doesnt match. all help would be great. Hi all, i've got a string ($currentcatid) which contains one number which changes dependant on which page the visitor is on.. ie it may be perhaps "23" or "17" . I need to do a check against this string to see if it contains any of the following values .. 31,32, 1, 24 . I cant remember how i did it before but i think it was with pipes.. something along the lines of if ($currentcatid =="31"||"32"||"1"||"24") { action } can anyone help? Thanks |