Trying to save result from PHP function in MySQL - php

I've created a simple customer signup form (signup.html) to capture 3 fields (email, subdomain and plan).
I also want to assign them a random password, I've lifted the code to generate this from this SO article (Generating a random password in php).
My PHP code (insert.php) is saving the form data fine into MySQL, but not the result from the randomPassword function, where it places "()" in the field instead of the randomly generated password I am hoping for.
I gather I'm not calling the result from the randomPassword() function properly. What am I doing wrong here?
SIGNUP.HTML
<form action="insert.php" method="post" class="inline-form">
<div class="form-group">
<label for="email">Your email address</label>
<input type="email" name="email" class="form-control input-lg" id="email" placeholder="Enter email">
</div><br><br>
<label>Select your plan</label><br>
<div class="radio">
<label>
<input type="radio" name="plan" id="plan" value="optionA" checked>
Option A
</label>
</div><br>
<div class="radio">
<label>
<input type="radio" name="plan" id="plan" value="optionB">
Option B
</label><br><br>
</div>
<div class="form-group">
<label for="subdomain">Pick your subdomain
</label>
<input type="text" name ="subdomain" class="form-control input-lg" id="subdomain">
</div>
<br><br>
<button type="submit" class="btn btn-teal" name="Sign Up">Sign me up!</button>
</form>
INSERT.PHP
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
$sql="INSERT INTO accounts (email, plan, subdomain, password)
VALUES
('$_POST[email]','$_POST[plan]','$_POST[subdomain]','$randomPassword()')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>

It doesn't look like you assign a variable to contain the password at all. Functions don't just execute on their own. Use the following:
$myPass=randomPassword();
$sql="INSERT INTO accounts (email, plan, subdomain, password)
VALUES
('$_POST[email]','$_POST[plan]','$_POST[subdomain]','$myPass')";
A function on it's own is just sitting there WAITING to be executed, but doesn't fire off on it's own. In this case, the function returns a value (the password it makes). To actually get it, you write code like $myPass=randomPassword(); which then executes the function and the value is passed into the variable.
As you don't appear to be a veteran, I will expand some more. If you aren't sure why to have a function rather than just execute the code in the first place, a function can be used over and over. Lets say I did the following:
$myPass1=randomPassword();
$myPass2=randomPassword();
With that one function I now have two totally different passwords stored in the variables. You can do all sorts of other fancy things, but think of a function as a snippet of code that is to be re-used within your code, hopefully on a number of occasions - without the need to have it written many times.

Perhaps this would work
$sql="INSERT INTO accounts (email, plan, subdomain, password)
VALUES ('$_POST[email]','$_POST[plan]','$_POST[subdomain]','randomPassword()')";

Related

How to convert Array to String? Database show me Array keyword instead of String

How to convert Array to String?
I insert data into the database in the
form of an array. Mysql database show me Array keyword instead of String. I have multiple text boxes with the same name. Interface
<?php
$conn = mysqli_connect('localhost', 'root', '','registeruserdb');
if(!$conn){
die("Failed to Connect. Contact Network Administrator");
}
// insert Category into category table
if (isset($_POST['submitbtn']))
{
$name = $_POST['Name'];
$relationship = $_POST['Relationship'];
$cnic = $_POST['Cnic'];
$contact = $_POST['Contact'];
$query="INSERT INTO registeruser(name,relationship,cnic,contactnumber) VALUES('$name','$relationship','$cnic','$contact')";
if(mysqli_query($conn, $query))
{
echo '<script>
alert("Added successfully.");
window.location="index.php";
</script>';
}
else
{
echo '<script>alert("ERROR: Could not able to execute $sql. ") </script>';
}
}
?>
Register Form:
<form class="form-horizontal" method="post">
<div class="control-group">
<div class="inc">
<div class="controls">
<input type="text" required name="Name[]" placeholder="Name"/>
<input type="text" required name="Relationship[]" placeholder="Relationship"/>
<input type="text" required name="Cnic[]" placeholder="Cnic#"/>
<input type="text" required name="Contact[]" placeholder="Contact#"/>
<button style="margin-left: 50px" class="btn btn-info" type="submit" id="append" name="append">
Add Textbox</button>
<br>
<br>
</div>
</div>
<button type="submit" class="btn btn-info" name="submitbtn"/>Submit</button>
</div>
</form>
You have two options to convert an array to string:
The simplest one is the implode function. This however can create problems when the delimiter you use is featured in any of the array-elements.
The second common method is serialize. It's a common practice to store a serialized array as string in a database, but know that it can lead to some headaches if you want to commit extended searches in the future based on that field. However for simply reading the data, you can just unseralize it.
But the best solution for this sort of problem is usually to create a table for your values with some foreign keys. It really depends on your intentions for the future: if you're expecting lots of records and you intend to query them a lot, I would really advise that method. If not, you can use the above methods to save some time.

Incrementing rows in the database

I have a form that adds / edits an event.
Namely, I wanted to extend it with the function of adding value automatically (just like increment and ++).
I have statistic_tips in the database containing two lines: stat_win and stat_false
Only during editing (because in principle the editing will usually consist in changing one record) after making changes, I would like to automatically increase the stat_win or stat_false line depending on the selected option (win, loss from results).
How do you achieve this, my dear?
Prompt? Possibly I would like to hear better solutions with a pleasant desire.
I apologize for a mistaken question, but I am a beginner
In red I marked the fragment, where I tried to figure it out, but unfortunately it failed.
<?php
function undefinedIndex(){
}
set_error_handler("undefinedIndex", E_NOTICE);
if(isset($_POST['add_tip'])){
$team1=$_POST['team1'];
$team2=$_POST['team2'];
$league=$_POST['league'];
$datentime=$_POST['datentime'];
$draw=$_POST['draw'];
$results=$_POST['results'];
$sql_insert="INSERT INTO premium_tips(datentime, league, team1, team2, draw, results) VALUES ('$datentime','$league','$team1','$team2','$draw','$results')";
if ($conn->query($sql_insert) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
if(isset($_POST['update_tip'])){
$team1=$_POST['team1u'];
$team2=$_POST['team2u'];
$league=$_POST['leagueu'];
$datentime=$_POST['datentimeu'];
$draw=$_POST['drawu'];
$results=$_POST['resultsu'];
$id=$_POST['id'];
[color="#FF0000"] $win1=$mysqli->query('SELECT stat_win FROM statistic_tips');
$loss1=$mysqli->query('SELECT stat_false FROM statistic_tips');
if($results=="win"){
$sql_insert="
UPDATE statistic_tips (stat_win) VALUES '$win1+=1'";
}
if($results=="loss"){
$sql_insert="
UPDATE statistic_tips (stat_false) VALUES '$loss1+=1'";
}[/color]
$sql_insert="
UPDATE premium_tips SET datentime='$datentime', league='$league',team1='$team1', team2='$team2',draw='$draw', results='$results' WHERE id='$id'";
if ($conn->query($sql_insert) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
And here is the file responsible for the editing form
$sql_get = "SELECT * FROM matches WHERE match_id='$q'";
$result = $conn->query($sql_get);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
echo '<form role="form" method="post" action=""
onreset="resetAction()">
<div class="form-group">
<label>Match info</label>
<input class="form-control" placeholder="Date of match" type="datetime-local" name="datentime" required><br>
<input class="form-control" placeholder="League" name="league" required><br>
<input class="form-control" placeholder="Stadium" name="stadium" required>
</div>
<div class="form-group">
<label>Home</label>
<input class="form-control" placeholder="Enter team name" name="team1" required>
</div>
<div class="form-group">
<label>Away</label>
<input class="form-control" placeholder="Enter team name" name="team2" required>
</div>
<button type="submit" class="btn btn-default" name="add_match">Add Match</button>
<button type="reset" class="btn btn-default">Reset</button>
</form>';
In fact, I mean automatic statistics on the WON / LOSS chart
At the beginning, when adding, each type has $ result = actual and when editing it is changed to either $ result = win or $ result = loss
I do not know if he combines well with these statistics.
UPDATE statistic_tips (stat_win) VALUES '$win1+=1'
This isn't valid SQL syntax.
What you're looking for is:
UPDATE statistic_tips SET stat_win = stat_win + 1 WHERE id = ?
Note that you don't need to select the previous value from the database beforehand -- the UPDATE query will increment it in place.

PHP - Insert elemens into an array

I'm working on a formular, but for the moment I just want to insert into an array my elements (I have books and authors).
I can display my books with author (name + surname) with the foreach, but I can't add more elements.
Here is the code with the form.
<H1>Exercice 2</H1>
<form method="POST">
<label for"code" >Number :</label>
<input id="code" name="code" type="number" />
<label for"title">Title :</label>
<input id="title" name="title" type="text" />
<label for"author" >Author :</label>
<input id="author" name="author" type="text" />
<button type="input" type="submit">Ok</button>
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = array();
$book['code'] = 123;
$book['title'] = "Legendes";
$book['author'] = array("David", "Gemmel");
foreach($book as $value){
$book['key'] = $value;
var_dump($book);
if (is_array($value)) {
foreach($value as $otherValue) {
echo($otherValue);
}
} else {
echo($value);
}
}
I did some searcch, but I don't think it works, it's using the array_push() method with the POST, but I don't know where I can manipulate my form into the array.
If you want some details, I'll be happy to do that =) I'm working on it, if i have some news, you will know =)
Have a nice day =)
1) Assignments are in reverse. Correct way:
$myVar = $myValue
2) You need to set the name attribute in your inputs in order to be sent:
<input id="code" type="number" name="code" />
Then you can access them like:
$_POST['code']
3) To add an element by key in an array, use:
$array['key'] = $value;
Your Exercise 2 have some mistakes :
First, your HTML inputs must have the name attribute to be retrieved by post:
<h1>Exercice 2</h1>
<form method="post">
<label>
<input name="code" type="number" />
</label>
<button type="submit">Ok</button>
</form>
With PHP, you can access to any input value using the name:
$code = $_POST['code'];
Now, I think you want to "add" several books using this HTML form without a storage system. The problem is you can not do this if for every a new request since all the elements you have in your array will be deleted each time you run a new post request. To keep this information you need to use some persistent storage system as a database or others.
Since you seem to want to keep the information for each book together, you need to use a multidimensional array - hence, you'll need to redo the whole thing. Here's a suggestion:
Form:
<h2>Exercice 2</h2>
<form method="post">
<label for"code">Number :</label>
<input id="code" name="code" type="number">
<label for"title">Title :</label>
<input id="title" name="title" type="text">
<label for"author-firstname">Author First Name:</label>
<input id="author-firstname" name="author-firstname" type="text">
<label for "author-lastname">Author Last Name:</label>
<input id="author-lastname" name="author-lastname" type="text">
<input type="submit" name="submit_book" value="Ok">
</form>
Fixed the name-problems, changed the heading (you never, ever use H1 for a form, H1 is strictly used for the site-wide heading/logo/name of site). Also changed the button into a simple input type="submit".
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = []; // changed this to modern PHP version array assignment
$book[0]['code'] = 123;
$book[0]['title'] = "Legendes";
$book[0]['author-firstname'] = "David";
$book[0]['author-lastname'] = "Gemmel"; // no reason to assign a separate array for first and last name, just use two array-keys
for ($c = 0; $c <= count($book); $c++) { //changed this to a for, counting the amount of entries in the $book array
echo 'Title: '.$book[$c]['title'];
echo 'Author: '.$book[$c]['author-firstname'].' '.$book[$c]['author-lastname'];
} // the content should probably be wrapped in a container of some sort, probably a <li> (and then a <ul>-list declared before the for-loop)
Now. None of this has anything to do with putting stuff INTO the array. That would be something like this (there isn't even a point of assigning the $_POST-variables for the code you posted. But, you can do something like this:
if (isset($_POST['submit_book'])) {
$title = $_POST['title'];
$code = $_POST['code'];
$author-firstname = $_POST['author-firstname'];
$author-lastname = $_POST['author-lastname'];
// however, if all you're doing is putting this into the array, no need to assigne the $_POST to variables, you can just do this:
$temp_array = ['code'=>$_POST['code'],'title'=>$_POST['title'],'author-firstname'=>$_POST['author-firstname'],'author-lastname'=>$_POST['author-lastname']];
$book[] = $temp_array;
}
So, that would replace the assigned variables at the beginning of your code.

How to insert mutliple records into mysql using foreach output?

I have a small app where the user adds 3-4 ticket in a single Form via the 'Add Another Ticket' button. These text boxes are generated via Jquery .append() and each ticket has 5 input boxes in it. Code Below
<form action="ticket-addcode.php" method="post" enctype="multipart/form-data" class="my-form">
<span id="tixmegaform">
<input type="hidden" name="Eventid" value="<?php echo $eventid; ?>" />
<div class="AddRow">
<label>Package Name</label>
<input class="requierd" type="text" name="ticketgroup" placeholder="Enter the Package Name. Most Preferably Event name" id="EN" value="<?php echo $ticketgroup; ?>">
</div>
<h5>Ticket 1</h5>
<div class="AddRow">
<label>Ticket Title</label>
<input class="requierd" type="text" name="tname[]" placeholder="Enter the Package Name. Most Preferably Event name" id="EN">
</div>
<div class="AddRow">
<label>Ticket Desc</label>
<input class="requierd" type="text" name="tdesc[]" placeholder="Enter the Details" id="EN">
</div>
<div class="AddRow">
<label>Ticket Cost</label>
<input class="requierd" type="text" name="tprice[]" placeholder="Enter the ticket Cost in Numbers. No Currency" id="EN">
</div>
<div class="AddRow">
<label>Ticket Book URL</label>
<input class="requierd" type="text" name="turl[]" placeholder="Enter the URL without http" id="EN">
</div>
<div class="AddRow">
<label>Time</label>
<input type="text" class="left requierd" name="eventTime[]" id="timeformatExample1" placeholder="Start">
</div>
<div class="AddRow">
<label>Date</label>
<input class="requierd" type="text" name="tdate[]" placeholder="Enter the Package Name. Most Preferably Event name" id="from">
</div>
</span>
<input type="submit" name="submit" class="add_field_button_submit">
</form>
</div>
</div>
</div>
<div class="add_field_button">Add Another Ticket</div>
</div>
So, when I hit the Submit button, a nested foreach runs through an array generated by the submit button. I'm able to fetch the values out of the array but somehow the output is not useful to me. Below is the foreach & the output
foreach ($_POST as $pos => $newarr) {
foreach($newarr as $res => $final){
echo $pos.'-----'.$final.'<br>';
}
}
Output
**tname-----VIP tix
tdesc-----Early Bird Desc
tdesc-----VIP Desc Tix
tprice-----5000
tprice-----10000
turl-----google.com
turl-----yahoo.com
eventTime-----00:30:00
eventTime-----00:00:45
tdate-----2-2-2016
tdate-----3-3-2016**
I tried to use an Insert Statement, but it just won't work. It seems that my foreach is resolving the sub array (tname array) and the outer array. If my foreach could just fetch values of different key and not the entire subarray, I would be able to insert the record into db.
Can you guide me on how to achieve this and where to put the INSERT Statement?
I don't think looping over $_POST as you have done will do you any good. Notice how the order of your information coming out makes it difficult?
Instead pick any of your array fields to determine first the number of tickets you have. Then use the number of tickets for iterating over each ticket. This way you can get the index of each group (ticket) of related information together. With the index, you can get all the information related for the group.
Once you have the necessary information, you can either store each information by doing one insert at a time or by doing one big insert. For simplicity, we shall use the former approach (using PDO).
Below is a rough and untested sketch of how it might look:
try {
$dbh = new PDO($dsn, $user, $password);
// prepare your SQL statement
$sth = $dbh->prepare("INSERT INTO table (title, desc, price, url) VALUES(?, ?, ?, ?)");
// loop over each ticket information
for ($i = 0, $numTickets = count($_POST['tname']); $i < $numTickets; $i++) {
$title = $_POST['tname'][$i];
$desc = $_POST['tdesc'][$i];
$price = $_POST['tprice'][$i];
$url = $_POST['turl'][$i];
// insert information into database
$sth->execute(array($title, $desc, $price, $url));
}
} catch (PDOException $e) {
// if something goes wrong, add some logic
}
For more information on PDO, read the documentation.
Use below format of SQL for insertion:
Example:
INSERT INTO tbl_name
(a,b,c)
VALUE (7,8,9);
As per your code:
$sql01 = "INSERT INTO tbl_name (tname,tdesc,tprice, turl) VALUES ";
foreach ($_POST as $pos => $newarr) {
$sql01 .= "(";
$sql01 .= isset($_POST['tname'])?array_merge($_POST['tname'],","):"";
$sql01 .= isset($_POST['tdesc'])?array_merge($_POST['tdesc'],","):"";
$sql01 .= isset($_POST['tprice'])?array_merge($_POST['tprice'],","):"";
$sql01 .= isset($_POST['turl'])?array_merge($_POST['turl'],","):"";
$sql01 .= ")";
}
mysql_query($sql01);

PHP, AJAX for Signup Form

I am trying to set up my first PHP site and I really want to do it the right way. I am working on the form located: http://www.bwgblog.com/signup.
I have set up the following form:
<p><form action="/signup/register.php" method="post">
<label for="first_name">First Name</label>
<input type="text" name="first_name" />
<label for="last_name">Last Name</label>
<input type="text" name="last_name" />
<label for="company">Company</label>
<input type="text" name="company" />
<label for="job_title">Job Title</label>
<input type="text" name="job_title" />
<label for="phone">Phone</label>
<input type="text" name="phone" />
<label for="email">Email</label>
<input type="text" name="email" />
<label for="username">Choose a Username</label>
<input type="text" name="username" />
<label for="password">Choose a Password</label>
<input type="text" name="password" />
<label for="confirm_password">Confirm Your Password</label>
<input type="text" name="confirm_password" />
<input type="submit" value="Get Started" />
</form>
And here is my PHP page, register.php:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("localhost","*******","******"); //Replace with your actual MySQL DB Username and Password
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bwgblog", $con); //Replace with your MySQL DB Name
$first_name=mysql_real_escape_string($_POST['first_name']);
$last_name=mysql_real_escape_string($_POST['last_name']);
$company=mysql_real_escape_string($_POST['company']);
$job_title=mysql_real_escape_string($_POST['job_title']);
$phone=mysql_real_escape_string($_POST['phone']);
$email=mysql_real_escape_string($_POST['email']);
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
$confirm_password=mysql_real_escape_string($_POST['confirm_password']);
$sql="INSERT INTO members (first_name,last_name,company,job_title,phone,email,username,password,confirm_password) VALUES ('$first_name','$last_name','$company','$job_title','$phone','$email','$username','$password','$confirm_password')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "The form data was successfully added to your database.";
mysql_close($con);
?>
I am trying to figure out how to add in AJAX such that it gives me two things. 1) The ability for it to check in realtime the username field as that field should be unique, and 2) the ability to have the confirm password field render a green checkmark if it == password field.
I have been looking all day for how to do this and can't get a clear look at it. Here is how the files are laid out:
signup (folder)
-> index.php
-> register.html.php
-> register.php
1) AJAX doesn't require the backend to be anything special - so the simplest solution there may be to have a 'usercheck.php' file that queries the DB for the username passed, then returns some form of true/false. You'll probably want to reply using JSON (this is easy if you have PHP 5 - see json_encode).
Regarding the AJAX frontend you'll find it easiest if you use an existing framework (I've used Mochikit and prototype, both seem fine) of which there are several. This should allow you to load the server's response easily.
If you have the AJAX use GET rather than POST (this is simpler) then you can test the response by just viewing the page with the appropriate query string. In any case using Firebug will allow you to view the calls in realtime.
2) There is no need to have the password check AJAX - that can be done simply using plain JavaScript: simply compare the .value properties of the two inputs.
Agreed with PeterJCLaw on all accounts except the choice of javascript framework. Here is how you could do it with jQuery:
// give the form an ID to use a better selector: ie: $('#myform')
// intercept form submit
$('form').submit(function(){
// check if passwords match; you might want to do more thorough validation
if($('input[name=password]').val()==$('input[name=confirm_password]').val()){
// make ajax post request and store the response in "response" variable
$.post('/signup/register.php', $(this).serialize(), function(response){
// process response here (assume JSON object has boolean property "ok"
if(response.ok==true){
// sweet, it worked!
alert('OK!');
}else{
// handle error
alert('Ooops');
}
}, 'json');
// stop the form from being submitted
return false;
}else{
// for the sake of simplicity
alert('Passwords don't match!);
}
});
Look at Jquery's validate extension.
It will simplify all of this. Checking remote values is simple too.
A relatively recent post on this with example code.
You can upload Jquery to your server, or google code hosts them. Using the google version greatly increases the chance that your customers will have already downloaded it also and can use their cached copy.
$fields = array('first_name','last_name','company','job_title','phone','email','username','password','confirm_password');
$dbfields = array(); $dbdata = array(); $dbfieldq = array(); $types = ''; //Setting Variable
foreach ($fields as $field){ //For Each Field
if (!isset($_POST[$field]){ header('Location: signup.php'); die('Please Fill in all fields, they are required'); } //Missing Field Error -- Doublecheck on serverside
array_push($dbdata, strip_tags($_POST[$field])); //Add Data - MySQLi Prepared Statements don't need to be escaped
array_push($dbfields,$field); //Add a field
array_push($dbfieldq,'?'); //Add a ?
$types += 's'; //Add a field type (string for all of these)
}
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db'); //Connect
if ($mysqli->connect_error) { //If there is a connect Error
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$names = explode($dbfields); //Explode the Field Names
$questions = explode($dbfieldq); //Explode the ?
$stmt = $mysqli->prepare("INSERT INTO DBName ($names) VALUES ($questions)");
$params = $this->paramValues;
array_unshift($dbdata, implode($this->paramTypes);
call_user_func_array( array( $stmt, 'bind_param' ), $params);
$stmt->bind_param($types, $code, $language, $official, $percent);
$stmt->execute();
$mysqli->close();
A better way to do the php... Use prepared statements and loops to prepare the variables.

Categories