I am having problems with my code.
I have a registration form which works fine apart form one area. The select option the user should select 'Yes' or 'No' from the options and then it should insert this 'Yes' or 'No' into the mysql database. Due to my code error it is not inserting anything. can you help me as to where i am going wrong please.
registration page code has this html among the form
<form action="register.php" method="post" autocomplete="off">
<label>Member<span class="req">*</span></label>
<select name="member">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</form>
this is then posted to my php page which has this code
<?php
$member = $mysqli->escape_string($_POST['member']);
$sql = "INSERT INTO members (member) "
.
"VALUES('$member')";
?>
obviously this is due to my lack of experience and is probably a really stupid mistake i have made but cannot see. I have spent a few days trawling around trying to get the answer but without any success.
Many Thanks
Use prepared statements. You won't need to escape string anymore.
$query = "INSERT INTO members (member) VALUES(?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s",$_POST['member']);//bind parameter to placeholder
return $stmt->execute() === true ? true : false;
You have written the query but have not executed it.
Use $mysqli->query($sql); to run the query.
Check this:
$sql = "INSERT INTO members (member) VALUES ('$member')";
$mysqli->query($sql);
Related
This question already has answers here:
Escape double quotes with variable inside HTML echo [duplicate]
(3 answers)
Closed 1 year ago.
First want to start off by saying that I am still a beginner developer but have gotten a long way in a short time and I am somewhat stumped. And yes I know my code might not be pretty in layout, but still learning, at least things are working.
I am creating something that is like a client portal for shows. A client signs up to do a show from an intake form. When they submit the form, it goes to Monday.com, creates a folder and sub folder in dropbox and then inserts everything into my Mysql database. I also then have another page (Assets) where they can upload files based on the show. Now if they have signed up for multiple shows, at the top of this page I have a dropdown box that grabs all the shows that is assigned to their used id. When they click on the show that they want to add files to and then click the "Choose Show For Asset Upload" button it goes back to the database to retrieve the dropbox path and the file request url and puts it into the code where those variables are assigned. So, everything is working great except when it comes to a show that has a single quote (apostrophe). I noticed this when I added a test show and everything went bonkers. I was able to figure everything out when it comes to making it correct in the code for Monday and Dropbox and even INSERTing it into the database. In the database column it has "Michael's" instead of "Michael\'s", so it's exactly how it should be in there. In the dropdown it actually shows "Michael's" but yet when I do an echo after clicking the button it shows "Michael" So that single quote is definitely the issue and this is where I don't know how to fix it, after much searching through the net.
In the dropdown it lists (Show Test, Did I Really Do It!!, Dudley, The Amazing MA, Lets See If This Works, Michael's).
Code is:
<div class="topdiv">
<h2 style="text-align: center;">Assets Upload</h2><br>
</div>
<?php
$userid = $_SESSION["userid"];
$sql = "SELECT * FROM intake WHERE userid = ?;";
$stmt = mysqli_stmt_init($con);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "There was an internal error!";
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $userid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
}
?>
<form class="formcenter" action="assets.php" method="post">
<select name="show" id="show">
<?php
while ($rows = mysqli_fetch_assoc($result)) {
$show = $rows['showtitle'];
echo "<option value='$show'>$show</option>";
}
?>
</select>
<input type="submit" name="chooseShow" value="Choose Show For Asset Upload"><br><br>
</form>
<?php
if(isset($_POST["chooseShow"])) {
$showTitle = $_POST["show"]; //WHEN I DO AN ECHO OF THIS IT SHOWS "MICHAEL" NOT "MICHAEL'S"
$sql = "SELECT * FROM intake WHERE userid = ? and showtitle = ? ;";
$stmt = mysqli_stmt_init($con);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "There was an internal error!";
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $userid, $showTitle);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rows = mysqli_fetch_assoc($result);
$path = $rows['dbxPath'];
$requestURL = $rows['requestURL'];
echo $show; //THERE JUST TO SEE WHAT IT WAS OUTPUTTING
echo $showTitle; //THERE JUST TO SEE WHAT WAS OUTPUTTING
}
}
?>
When I do the two echos at the end of the code $show = "Michael's" and $showTitle = "Michael". So I do know that the correct way is coming through but just can't grab it to put in the last $sql variable to use as the $showTitle Granted, I am assuming the $show is showing "Michael's" because it's the last show in the loop. BUT when I tested $show instead of $showTitle in the mysqli_stmt_bind_param statement it actually worked, so I know it's possible. Just need to know how to get the full "Michael's" into my $showTitle variable.
Thank you for taking the time to look through this longwinded (trying to give you as much info as possible) question and appreciate any help and advice.
-Michael
Your problem is here:
echo "<option value='$show'>$show</option>";
The single quotes in the variable $show are interfering with the single quotes wrapping the value.
Change it to this:
echo '<option value="'.$show.'">'.$show."</option>";
This explicitly concatenates the parts of the string rather than interpolating it. It gives better control over what quotes are used and where.
I have the following form:
<form id ="classadderform" action="formsubmit.php" method="POST">
<input type ="checkbox" name="note" value = "Note1"></input>
<input type="submit" value="Click Me" style="width:300px;">
</form>
Upon submit, the code redirects to formsubmit.php. Part of the code there is the following:
$db = new mysqli("sql...byethost8.com", "b8_163//....(database info));
$id = $_SESSION['id'];
.......
if(isset($_POST['note'])){
if($id){
$db->query("UPDATE answers SET WordLevel = 'Difficult' WHERE user_id=$id"); //<<<UPDATES SUCCESSFULLY
$notevalue=$_POST['note'];
$db->query("INSERT INTO answers (user_id, ValueColumn) VALUES ($id,'$notevalue')"); //<<<<<DOESN'T UPDATE
The WordLevel column updates successfully, but the value of the input named note does not insert into the column titled ValueColumn. This was working in my code a few days ago but it somehow stopped working. I tried different iterations of single quotes around $id and $notevalue but nothing seems to resolve the issue.
Any help would be much appreciated!
Execute and clear before the second query.
O you can try concating queries together using semicolon
$db->query("FIRST QUERY ; SECOND QUERY");
If you dont need the output of first query.
PDO multiple query
mysqli multiple query
might also help real_query
I have created a drop down list as well a input type for for category and name but in both the case as i click next it directs me to another page but nothing saves in my database.
company_account is the table name in which data has to be inserted it has four rows id, category, cname, about
<?php include( "./inc/header.inc.php");
require( "./inc/connect.inc.php"); ?>
<div>
<form action = "payment.php" method= "POST">
<select id="category" name="category" class="old_ui_selector">
<option value="0" selected="1">Choose your category</option>
<option value="">Accounting Firm</option>
<option value="">Agriculture</option>
<option value="">Automotive</option>
<option value="">Aerospace/Defence</option>
<option value="">Building Material</option>
</select>
</div>
<br>
<input type = "text" name="cname" placeholder= "Name"/>
<br><br>
By clicking Next you agree to the Terms and Conditions.
<br>
<input type = "submit" name="comp" value="Next"/>
</form>
<?php
if(isset($_POST['comp']))
{
$category=$_GET['category'];
$cname = $_POST['cname'];
$ins=mysql_query("insert into company_account (category) values ('$category')");
$insert = mysql_query("INSERT INTO company_account VALUES ('','$category','$cname','$about')");
if($ins)
if($insert)
{
echo "<br>".$category."inserted";
}
else
{
echo mysql_error();
}
}
?>
You have a few issues there, the first is you are using mysql, either update it to mysqli or better still PDO.
Second your form is submitting using POST and yet you try to collect the category using GET.
You also need to supply the contents of your connect.inc.php WITHOUT THE IP AND PASSWORD so people can have a look at the config.
I would suggest before going any further you have read here and get a better understanding before you proceed.
https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Best of luck.
Note: mysql: This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
You have provided with the form action and that will redirect after clicking the submit button.
You have written the INSERT STATEMENT in the same page itself and that will not even work for you.
First Remove up the action="" and then you redirect it based on the data saved.
HTML:
<form action = "" method= "POST">
</form>
And you Option value is missing out values and after the form is submitted the values will not be entered into the DB. Hence you need to do the following.
Replace:
<option value="">Accounting Firm</option>
With:
<option value="Accounting Firm">Accounting Firm</option>
PHP Code for Insert:
You Insert Code will not work since you have not provided with the table values for insert operations.
Syntax:
INSERT INTO TABLENAME(`columnname1`,`columnname2`,.....) VALUES(VALUE1,VALUE1,....)
Hence you are advised to use the correct table structure for the Operations and then insert the data.
INSERT QUERY:
$insert = mysql_query("INSERT INTO company_account(`category`,`name`,`about`) VALUES ('$category','$cname','$about')");
You can insert all in the single query itself and then redirect using the header location.
Use header Location for redirection to particular page after the data has been saved.
header('location : http://www.google.co.in');
PHP PART:
<?php
if(isset($_POST['comp']))
{
$category=$_POST['category'];
$cname = $_POST['cname'];
$insert = mysql_query("INSERT INTO company_account(`category`,`name`,`about`) VALUES ('$category','$cname','$about')");
$rows = mysql_affected_rows();
if($rows=0)
{
echo mysql_error();
}
else
{
ob_start(); // Refresh the Output Buffer
header('location: http://www.google.co.in');
exit;
}
}
?>
Note: $about you are using in the Insert Statement but no values are provided over to the Insert Statement. Please check to that.
I have a post text website on http://www.youngcreatitivy.se
You see on http://www.youngcreativity.se/post.php that I have a post method. And on the bottom of the page I have like a option to choose which category your text is in. I've founded this code for inserting value from select box into my database. Here it is:
<?php
//insert category to database
if(isset($_POST['qty'])) {
// Fetch and clean the <select> value.
// The (int) makes sure the value is really a integer.
$qty = (int)$_POST['qty'];
// Create the INSERT query.
$sql = "INSERT INTO `table`(`quantity`)
VALUES ({$qty})";
// Connect to a database and execute the query.
$dbLink = mysql_connect('server', 'username', 'password') or die(mysql_error());
mysql_select_db('database_name', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
// Check the results and print the appropriate message.
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
?>
Thats the Php code.
Here's the html code:
Qty: <select name="category">
<option value="1">Quote</option>
<option value="1">Poem</option>
<option value="1">Novel</option>
</select>
<br>
<input type="submit">
</select>
I understand the code, but how should I create the database in phpMyAdmin? And how can I get so that If I click submit after choosing the category and typed in my text it post the text and it writes which category I chosen in the database?
Please, help me!
I am guessing your first language is not English - 'Qty' is a common abbreviation for 'Quantity', so the code you are re-using is more about numbers.
You need to change the original <select> to something like -
<select name="category">
<option value="Quote">Quote</option>
<option value="Poem">Poem</option>
<option value="Novel">Novel</option>
</select>
As your code is, the select will only ever return 1.
Also, you need to escape the value returned before you store it in the database. mysql_real_escape_string is your friend in this case - http://php.net/manual/en/function.mysql-real-escape-string.php - otherwise you are open to sql injection.
If you are in localhost. Then you have to go to
http://localhost/phpmyadmin
There you find the way to create database and tables you can get easily. But you r in server if you have cokntrol panel there you see phpmyadmin with logo. There you click on that your phpmyadmin will be opened.Same as localhost. Hope this helps to you.
Ramsai
i write a command, or i fill up parameter value from user input field. click the button, send this command to php and send resultant value back to html to display.
for example. on html page :
select ___ from ____,
two available input field i fill up with "tablenameone" and "valueone". then, result will be printed on html text field on the same page.
what i do know is those value can be sent(perhaps) as in such format
$('input[name="talbename"]')
$('input[name="value"]')
example.com?tablename=tablenameone&value=valueone
and from php side i use
$sql="SELECT '$_GET['value']' FROM '$_GET['tablename']';
what i dont know is that....how exactly should i perform this in a click function? its for sure using ajax. but how can i produce example.com?tablename=tablenameone&value=valueone
and where should i put $('input[name="value"]')
thanks in advance :D
You must not use direct input in your queries as you will be open to SQL injection attacks.
$sql="SELECT '$_GET['value']' FROM '$_GET['tablename']';
Instead, use the following:
$column = $_GET['value'];
$table = $_GET['tablename'];
$sql = sprintf("SELECT %s FROM %s;",
mysql_real_escape_string($column),
mysql_real_escape_string($table));
Although you are still exposing too much "inside information" by giving people a page that tells them all of your table and column names!
Anyway, here is a complete example;
<form method="post" action="">
<fieldset>
<legend>Select Data</legend>
<p><label>Table<br>
<select name="table">
<option value="tblStudents">Students</option>
</select></label></p>
<p><label>Table<br>
<select name="column">
<option value="firstname">First Name</option>
<option value="lastname">Last Name</option>
</select></label></p>
<p><input type="submit" name="submit" value="submit">
</fieldset>
</form>
<?php
$connection = mysql_connect("servername:3306", "user", "password") or die ('Error connecting to mysql');
mysql_select_db("databasename");
$column = mysql_real_escape_string($_POST['column']);
$table = mysql_real_escape_string($_POST['table']);
$sql = sprintf("SELECT %s FROM %s;",
$column,
$table);
$result = mysql_query($sql) or die(mysql_error());
echo '<ul>';
while($row = mysql_fetch_array($result)) {
echo '<li>' . $row[$column] . '</li>';
}
echo '</ul>';
mysql_close($connection);
?>
Seeming as though noone has actually answered the question (although they are all good points, I will assume there is a reason for you doing this), I will answer:
$('form[name=formname]').submit(function(e){
e.preventDefault;
var tablename = $('input[name="tablename"]').val();
var value = $('input[name="value"]').val();
$.get("example.php?tablename="+tablename+"&value="+value, function(data){
$('body div').text(data);
})
});
PHP:
$sql=mysql_query("SELECT '$_GET['value']' FROM '$_GET['tablename']'")or die(mysql_error());
$sqlOutput = mysql_fetch_array($sql);
echo "<pre>";
print_r($sqlOutput);
echo "</pre>";
Obviously replace formname with your form name, body div with the name of the element you want the output to go in and all other identifiers replaced where seen fit. Then change the output in the PHP to suit your needs.
Again, do bear in mind the posts regarding SQLi, because you have yourself a very serious problem there.
You really want to make sure you are not open to SQL injection.
You could use mysql prepared statements
or
use the php function mysql_real_escape_string($_GET['value'])
Read this thread:
How can I prevent SQL injection in PHP?
I'm not sure what you mean by the click function.