I've asked once but I didn't get the answers.
var phoneno = /^\+?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
this is how I learnt to validate the numbers + error and...
I also have the Mobile bigint(20) & country varchar(200), in my table "users".
what I want to do is to use another file "countries.php" to get their codes in mobile input in "signup.php" page and store them both into the database.
for example, user chooses 'US +1' the country code will appear in mobile section.
$countryArray = array(
'AD'=>array('name'=>'ANDORRA','code'=>'376'),
'AE'=>array('name'=>'UNITED ARAB EMIRATES','code'=>'971'), ...
function countrySelector($defaultCountry = "", $id = "", $name = "", $classes = ""){
global $countryArray; // Assuming the array is placed above this function
$output = "<select id='".$id."' name='".$name."' class='". $classes."'>";
foreach($countryArray as $code => $country){
$countryName = ucwords(strtolower($country["name"])); // Making it look good
$output .= "<option value='".$code."' ".(($code==strtoupper($defaultCountry))?"selected":"").">".$code." - ".$countryName." (+".$country["code"].")</option>";
}
$output .= "</select>";
return $output; // or echo $output; to print directly
}
not to mention I downloaded the file zip. and I don't really know how to add or use the " use", please be more specific, like give with examples. thanks
Related
Im working on a JS shopping cart site and I am trying to send the cart details to mail at the check out function using php mail,here im passing my cart details to php via ajax.
in php when try to send all the cart values using foreach im only able to recive the just last row of cart as foreach is repalcing the previous value
how do i retrive the cart values and send them in a format
js
function SendMail() {
var tableContent = localStorage.getItem('productsInCart');
$.post('read.php', {tableContent: tableContent}, function (data) {
console.log(tableContent);
});
}
php
if (isset($_POST['tableContent'])) {
$tableContent = json_decode($_POST['tableContent']);
foreach ($tableContent as $tableContent) {
$name = ($tableContent->name);
$price = ($tableContent->price);
$quantity = ($tableContent->inCart);
}
$mailTo = "xxxxxxxxxxxxx";
$Subject = " order details ";
$headers = "from :" . $contact;
$txt = "New registration \n Item:" . $name . "\n Quantity:" . $quantity . "\n Price:" . $price . "\n\n\n CUSTOMER DERAILS\n\n Name:" . $contact . "\n Reg No:" . $reg;
mail($mailTo, $Subject, $txt, $headers);
header("location: read.php?mailsend");
}
You're currently overwriting the same variables on each iteration of the loop, which is why they will only contain the last entry.
You should append the values instead, doing something like:
$tableContent = json_decode($_POST['tableContent']);
// Define a variable to store the items in
$items = '';
// Let's add a total sum as well
$total = 0;
// Let's also use different variable names here
foreach ($tableContent as $item) {
// Append to the variable (notice the . before the =)
$items .= 'Item: ' . $item->name . "\n";
$items .= 'Quantity: ' . $item->inCart . "\n";
$items .= 'Price: ' . $item->price . "\n\n";
// Add the price to the total (I'm assuming that the price is an integer)
$total += $tableContent->price;
}
Now when outputting the email body, we have all the items and the total in those variables:
$txt = "New registration \n" . $items . "Sum total: " . $total . "\n\n\n CUSTOMER DERAILS\n\n Name:".$contact."\n Reg No:".$reg;
As you can see, I changed the layout of the mail a bit since the cart seems to be able to contain several items while your email body was written as if only could contain one.
A warning about this approach
You shouldn't get the cart values, like name and price, from the client in a POST request like this. The client should only send the item id and quantity and then you would fetch the name and price from a database or similar in the backend. Otherwise, anyone can modify the price to be anything they want before it's posted. Never ever trust user data.
I have managed to get this code to work for an application -- http://twitter.github.io/typeahead.js/ but, the problem I have run into, is that I need to be able to re-load the data. I would rather not duplicate the code to do this, although it's an option, it seems kind of silly. I have inserted some PHP into my JavaScript to create an array for the dropdown list, and it works great. But if I stuff it into a function, and then try to call the function in the document open, it doesn't work (nothing appears to happen).
$(document).ready(function()
{
// call function when page loads(?)
getAwards();
}); // end document.ready ...
This is the PHP code, if I comment out the JavaScript function parts it runs and the typeahead code sees the value of the array. If I put it into the function, it doesn't execute despite being called above, and I have no data for the typeahead code ...
function getAwards(
{
// build array for use with typeahead:
<?php
$sql_statement = "select title from awards order by title desc limit 1";
$aw_result = mysqli_query( $connect, $sql_statement );
$aw_row = mysqli_fetch_array( $aw_result );
$last_award = $aw_row["title"];
// need to rewind table:
mysqli_data_seek( $aw_result, 0);
// start from the top:
$sql_statement = "select title from awards order by title";
$aw_result = mysqli_query( $connect, $sql_statement );
$count = 0;
$out = 'awards = [';
while ( $aw_row = mysqli_fetch_array( $aw_result ) )
{
// the quotes deal with forcing this to handle
// branch names with apostrophes in them ...
$count++;
$out .= '"'. $aw_row["title"] . '"';
if( $aw_row["title"] != $last_award )
{
$out .= ',';
}
}
$out .= ']';
echo $out . "\n";
?>
})
I need to be able to update the data, and reload the list while working on the form (I am working that out in my fuzzy brain, but anyway I'll get to that -- currently intend to click a button to update the list used by the typeahead, which is why I want a function ...)
Any suggestions are gratefully accepted. I am at a loss ...
I've created a search page that sends results to a table with the ability to click on a specific record which then opens another page in the desired format.
I'd like to do is be able to open different formatted pages based on the data returned in the search query but I'm having a bit of trouble pulling it all together.
Here's the PHP used to request and retrieve the data from the database, as well as populate it in a table where each record can be selected and used to populate a planner page with all the proper formatting:
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
Now the fun part. I want to open different pages based on the information contained in the record. I've got it working for the pkey variable by itself with a single javascript function. However, if I want to open a differently formatted page using the same function using if, else statements, the table only populates with the link page based on the last record compared. Here is my attempt to get the JavaScript with the if, else statements working but it only uses the format of the last record that's compared.
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
} else {
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
How do I get the 'Get Planner' button to open the correctly formatted planner page based on the users specific information?
To make things easier I'd suggest the following:
Do the logic already in php when generating the html-table (and the link).
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
if($rsv) { // thats basicly the same as !=0
$target='../php/plannerR.php'
} else {
$target='../php/planner.php'
}
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td>";
echo "<td>".$row['rank']."</td><td>".$row['ment1']."</td>";
echo "<td><a class='button styleIt' href='".$target."?pkey=".$pkey."&rsv=".$rsv."'>Get Planner</a></td></tr>";
}
If you wanna stick to your js solution (which is more hassle unless you really need it) you can of course go with the solution from my comments that you already successfully implemented (and posted as answer so others can see the implementetion).
Thanks to Jeff I played around a bit with bringing both variables into the function and got it to work. Final code below.
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."','".$rsv."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey, rsv) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
}
else{
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
I have been having problems with a form of an website of mine. The form values are equal to their corresponding $_POST values, which are the parameters used for updating the database.
I do not want for empty form values to be updated. However, I don't want any of the input areas to be obligatory.
That means that I would be able to update only specific content, not needing to type the values in the input areas I do not want to update. I'm having problems with this, however. Empty form values are being uploaded, so the values in the database are being changed into blank values. I've looked for tutorials in SO and over the internet, and the only (functional) ones are those which turn input boxes into obligatory. That is not how I intend it to work, so it doesn't fit.
I think the best way to do this, and I am not sure, is to change, through javaScript, the "name" attribute of the input areas into blank when the submit button is set IF the values equal empty or null. I do not know how to do this, nor do I know if this is possible, or the best way.
Here is my current code on the matter:
(first, the form an the javascript)
<script>
function validade(){
var formId = document.getElementById("configForm");
var allInputs = formId.getElementsByTagName("input");
var input, i;
for (i=0; input = allInputs[i]; i++){
if (input.value == null || input.value == "") {
input.name = "";
}
}
}
<form method="post" action="" id="configForm">
<label for="home">Home:</label>
<br>
<input type="text" id="home" name="home">
<br>
<label for="apendix">Apêndice:</label>
<br>
<input type="text" name="apendix">
<br>
<label for="about">Sobre:</label>
<br>
<input type="text" name="sobre">
<br>
<label for="contato">Contato:</label>
<br>
<input type="text" name="contato">
<br><br>
<input type="submit" value="Carregar" name="submit">
</form>
<?php require_once('editaForma.php'); ?>
(Secondly, the database query and $_POST values:)
<?php //credentials
if (isset($_POST["submit"])){
$server = 'hypotetical';
$user = 'hypotetical';
$pw = 'hypotetical';
$BD = 'hypotetical';
//estabelece a conexão
$conn = mysqli_connect($server, $user, $pw, $BD);
if (!$conn) {
die ('<span style="color: #FF0000;">"connection failed: "</span>' . mysqli_connect_error());
}
$home = $_POST["home"];
$apendix = $_POST["apendix"];
$sobre = $_POST["sobre"];
$contato = $_POST ["contato"];
$query = "UPDATE form SET
home= '$home',
apendix= '$apendix',
sobre= '$sobre',
contato= '$contato'
WHERE id='1'";
//$query = "INSERT INTO form (home, apendix, sobre, contato) VALUES ('$home', '$apendix', '$sobre', '$contato')";
if (mysqli_query($conn, $query)){
echo "Alterações feitas com sucesso";
} else {
echo "ERRO!" . $query . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
Yes, I know the DB is prone to SQL injection. I'm trying to get everything up and running first, and once all of this is set, I'll look onto security matters before the website is online.
I've been having this problem for over a week and can't figure a way out of it.
Thank you for your time and attention, in advance.
EDIT
I wish I could select two answers for the solving ones. Both of them right down led me to the solving of the problem, each helping me to see the holes in my code. As I cannot choose both, I chose the one who helped me to solve the last issues. Thank you all so much!
Build your query dynamically, by skipping empty values
$p = &$_POST; //make $p refer to $_POST
$query = "UPDATE from SET ";
if($p['home']) $query .= " home = '$p[home]' ,";
if($p['apendix']) $query .= " apendix = '$p[apendix]' ,";
if($p['sobre']) $query .= " sobre = '$p[sobre]' ,";
if($p['contato']) $query .= " concato = '$p[contato]' ,";
$query = trim($query, ','); //remove any trailing comma
$query = "WHERE id = 1";
you can then execute the query. Oh and don't forget to check that at least 1 of the variables was available. If they're all empty, don't execute.
And yeah, your code is highly vulnerable.
Glaring security holes aside, I would usually build up a string, something like this:
$home = $_POST["home"];
$apendix = $_POST["apendix"];
$sobre = $_POST["sobre"];
$contato = $_POST ["contato"];
$query = "UPDATE form SET ";
if(!empty($home)) {
$query .= "home= '$home',";
}
if(!empty($apendix)) {
$query .= "apendix= '$apendix',";
}
if(!empty($sobre)) {
$query .= "sobre= '$sobre',";
}
if(!empty($contato)) {
$query .= "contato= '$contato',";
}
// strip off any extra commas on the end
$query = rtrim($query, ',');
$query .= "WHERE id='1'";
Building the query with the comma at the end also allows you to easily add more options later if you need to.
I did it, in a simple way using NULLIF
set potato = NULLIF(potato,'')
I am trying to create a D3 line graph that will display a graph specific to the item that is selected in the drop-down menu. I have one script that queries my MySQL database and fills a drop-down menu with all of the correct options. From there, I want to click on an option and go to another page that creates a line graph based off of that selection. When I click on an option, I use json_encode to create a JSON object that should be compatible with D3.
I have another script that deals completely with drawing the graph and try to use d3.json to get the JSON object that is created when the specific selection is clicked. Whenever I try to load the graph page, it is completely blank. I am not sure if what I am trying to do is even possible. I have not tried including the drop-down in the same script as the one that creates the graph but do not think that I will be able to get the information from the database the same way.
Any guidance or suggestions would be greatly appreciated. I can post the code later if it is determined what I am trying to do is possible. Thanks!
EDIT:
This is the script that queries my database for the users that are put in the drop-down menu and then queries the database again for that selection's data. The drop-down menu has the desired result and the data is correctly echoed as well.
<?php
if (isset($_POST['name']))
{
$out = $_POST['name'];
$temp = explode(",", $out);
$populate_selection = "SELECT id, lastname, firstname FROM users WHERE id != '$temp[0]' ORDER BY lastname";
$out = $temp[1] . ', ' . $temp[2];
$student_hours = "SELECT ai_averages.user_id, ai_averages.title, ai_averages.hours FROM ai_averages INNER JOIN users ON ai_averages.user_id = users.id WHERE $temp[0] = ai_averages.user_id";
}
else
{
$temp[0] = " ";
$populate_selection = "SELECT id, lastname, firstname FROM users ORDER BY lastname";
$student_hours = "SELECT ai_averages.user_id, ai_averages.title, ai_averages.hours FROM ai_averages INNER JOIN users ON ai_averages.user_id = users.id WHERE $temp[0] = ai_averages.user_id";
$out = " ";
}
$result = $mysqli->query($populate_selection);
$option = "<option value= '{$temp[0]}'>$out</option>";
while($row = mysqli_fetch_assoc($result)) {
$option .= "<option value = '{$row['id']}, {$row['lastname']}, {$row['firstname']}'>{$row['lastname']}, {$row['firstname']} </option>";
}
if($student_results = $mysqli->query($student_hours))
{
$data = array();
for ($x = 0; $x < mysqli_num_rows($student_results); $x++)
{
//this array contains the data that I want in my graph
//the correct data is echoed every time that I click on the different choices
$data[] = mysqli_fetch_assoc($student_results);
}
echo json_encode($data, JSON_PRETTY_PRINT);
}
?>
<form id = "hello" method = "POST" >
<select name = "name" onchange = 'this.form.submit()'> <?php echo $option; ?> </select>
</form>
I then try and use d3.json("filename.php", etc) to get the information from the $data array but this has not worked.