I'am trying to do very simple php page and have some kind of problem here. the page works and everything but there is nothing coming to mysql. When I press submit it prints insert into DrinkHistory(CustomerId,DrinkId,SellerId) values('1','3','2')Your Data Inserted. But when I login to phpmyadmin there is nothing in DrinkHistory table.
the code is below
<?php
// Create connection
$con=mysqli_connect("localhost","******","*******","test");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Mene kotii ku et mitää osaa: " . mysqli_connect_error();
}
// Insert Data
#$a=$_POST['CustomerId'];
#$b=$_POST['DrinkId'];
#$c=$_POST['SellerId'];
if(#$_POST['submit'])
{
echo $s="insert into DrinkHistory(CustomerId,DrinkId,SellerId) values('$a','$b','$c')";
echo "Your Data Inserted";
mysql_query($s);
}
?>
<center>
<form method="post">
<table width="100%" height="245" border="1" bgcolor="#00CCFF">
<tr><td width="112" height="26">Asiakas</td>
<td width="100"><input type="radio" name="CustomerId" value="1"/>Jokirinne Niko</td>
</tr>
<tr><td rowspan="2">Juoma</td>
<form method)="post">
<td height="28"><input type="radio" name="DrinkId" value="2"/>Kalja</td>
<td height="28"><input type="radio" name="DrinkId" value="3"/>Lonkero</td>
<td height="28"><input type="radio" name="DrinkId" value="4"/>Siideri</td>
<td height="28"><input type="radio" name="DrinkId" value="5"/>Fisu</td>
<td height="28"><input type="radio" name="DrinkId" value="6"/>Tequila</td>
<td height="26"><input type="radio" name="DrinkId" value="7"/>MustikkaShotti</td>
</tr>
<td height="33"></tr>
<tr><td rowspan="3">Myyjä</td>
<td><input type="radio" name="SellerId" value="1"/>Niko Jokirinne</td>
<tr>
<td><input type="radio" name="SellerId" value="2"/>Tanya Lickorish</td>
<tr>
<tr><td height="62"><input type="submit" name="submit" value="Juo"/></td></tr>
</table>
</form>
</center>
</body>
</html>
You seem to be omitting the connection string (using mysql_query instead of mysqli_query) and error verification. Try this:
<?php
// Create connection
$con=mysqli_connect("localhost","******","*******","test");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Mene kotii ku et mitää osaa: " . mysqli_connect_error();
}
// Insert Data
#$a=$_POST['CustomerId'];
#$b=$_POST['DrinkId'];
#$c=$_POST['SellerId'];
if(#$_POST['submit']) {
echo $s = "insert into DrinkHistory(CustomerId,DrinkId,SellerId) values('$a','$b','$c')";
if (mysqli_query($con, $s)) {
echo "Your Data Inserted";
} else {
echo "Error inserting data: ".mysqli_error();
}
}
?>
You have several database libraries to choose from but, once you decide, you need to stick to one. You cannot start a connection with the new mysqli extension:
$con=mysqli_connect("localhost","******","*******","test");
... and then try to query the database with the legacy deprecated functions:
mysql_query($s);
If you are not getting a blattant error message on screen you've probably failed to configure PHP to display error messages in your development box.That's something you need to fix before you go further; it's impossible to code without the aid of error messages. Here's a brief explanation.
Finally, you verify if your connection fails:
if (mysqli_connect_errno($con))
... but you don't test if your query fails.
Related
Sorry, I admit, a little speak english :( so, I would like to ask for your help, a relatively simple problem. Given a form, which appears in openModal, clicking on a link(Add new):
Add New
<div id="openModal" class="modalDialog">
<div>
X
<form action="upload.php" method="post">
<table align="center" class="table-form">
<tr>
<td><label for='username' >Username:</label></td>
<td><input name='username' id='username' value='' type='text'></td>
</tr>
<tr>
<td><label for='e-mail'>e-mail:</label></td>
<td><input name='e-mail' id='e-mail' value='' type='text'></td>
</tr>
<tr>
<td colspan="2" align="center"><button type="submit" name="Submit">Save</button></td>
</tr>
</table>
</form>
</div>
</div>
and click save and run the upload.php, and skips the upload.php page, if successfully saved to the database, php file and print, that "Successfully uploaded!" This is upload.php:
<?php
$db= mysql_connect("localhost","root","");
if(!$db)
{
echo "Could not connect to the database";
exit;
}
$db_selected = mysql_select_db("test",$db);
if(!$db_selected)
{
die("CAN'T USE THIS DATABASE: ".mysql_error());
}
if($_POST["username"] !="" && $_POST["e-mail"] !="")
{
$id = mysql_insert_id();
$username = $_POST["username"];
$e-mail = $_POST["e-mail"];
$sql = "INSERT INTO `test` VALUES ('$id','$username','$e-mail')";
$result = mysql_query($sql,$db);
echo "Sucessfully upload!<br />\n";
}
?>
The connections are good, but I would like, that not to redirect the upload.php, if successful upload, but remains open to the modal, and in open modal appear to be successful upload (which provides the upload.php), and can be ok, and return to the main page!
I hope that was understandable, to help, thank you in advance! :)
cannot find out what is the problem...for example i want to add 2 row of data...when i press the + button...my data just typed will gone(looks like refresh)...and database will only store the 2nd row of data...1st one will not store. please help me find out the answer. thank you~
<?php if($_POST['btnPlus1'])
$_SESSION['count1'] += 1;
else if($_POST['btnMinus1'])
$_SESSION['count1'] -= 1;
$AddEducationalQ = "INSERT INTO tbleducational(Id,University,Level,Specialization,Year) VALUES('".$_POST['txtStaffIc']."','".strtoupper($_POST['txtUniversity'])."','".strtoupper($_POST['sLevel'])."','".strtoupper($_POST['txtSpecialization'])."','".$_POST['txtYear']."')";
$AddEducationalResult = mysql_query($AddEducationalQ,$link); ?>
<tr>
<td>
<fieldset>
<legend>Educational Background</legend>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<?php
for($tempfield = 1; $tempfield <= $_SESSION['count1']; ++$tempfield)
{?>
<fieldset>
<legend><?php echo $tempfield ?></legend>
<table width="200" border="0">
<tr>
<td>University</td>
<td>Level</td>
<td>Specialization</td>
<td>Year Graduated</td>
</tr>
<tr>
<td>
<input type="text" name="txtUniversity" id="txtUniversity" /></td>
<td>
<select name="sLevel" id="sLevel">
<option></option>
<option>Diploma</option>
<option>Degree</option>
<option>Master</option>
<option>Doctor</option>
</select>
</td>
<td>
<input type="text" name="txtSpecialization" id="txtSpecialization" />
</td>
<td>
<input type="text" name="txtYear" id="txtYear" />
</td>
</tr>
</table>
</fieldset>
<?php
}?>
</td>
</tr>
<tr>
<td colspan="4" align="center"><input type="submit" name="btnPlus1" id="btnPlus1" value="+" /> <input type="submit" name="btnMinus1" id="btnMinus1" value="-" /></td>
</tr>
</table>
</fieldset>
</td>
</tr>
Ok first you'll have to change your form element to:
<form method="post" action="filename.php" accept-charset="utf-8">
Make sure you change filename.php to the filename of this code.
Now you'll have to make a choice. You can either continue with mysql_*, which is deprecated and extremely insecure! Or you can upgrade your code to PDO() instead.
If you wish to continue with mysql_*, change your PHP part to:
if(isset($_POST['txtStaffIc'], $_POST['txtUniversity'], $_POST['sLevel'], $_POST['txtSpecialization'], $_POST['txtYear'])){
$AddEducationalQ = "INSERT INTO tbleducational(Id,University,Level,Specialization,Year) VALUES('".$_POST['txtStaffIc']."','".strtoupper($_POST['txtUniversity'])."','".strtoupper($_POST['sLevel'])."','".strtoupper($_POST['txtSpecialization'])."','".$_POST['txtYear']."')";
mysql_query($AddEducationalQ,$link) or die(mysql_error());
echo "Data succesfully added to database.";
}
If you wish to upgrade to PDO() instead, change your PHP part to:
if(isset($_POST['txtStaffIc'], $_POST['txtUniversity'], $_POST['sLevel'], $_POST['txtSpecialization'], $_POST['txtYear'])){
$AddEducationalQ = "INSERT INTO tbleducational(Id,University,Level,Specialization,Year) VALUES(':txtStaffIc',':txtUniversity',':sLevel',':txtSpecialization',':txtYear')";
$prepare = $pdo->prepare($AddEducationalQ);
$prepare->bindValue(":txtStaffIc",$_POST['txtStaffIc']);
$prepare->bindValue(":txtUniversity",strtoupper($_POST['txtUniversity']));
$prepare->bindValue(":sLevel",strtoupper($_POST['sLevel']));
$prepare->bindValue(":txtSpecialization",strtoupper($_POST['txtSpecialization']));
$prepare->bindValue(":txtYear",$_POST['txtYear']);
if($prepare->execute()){
echo "Data succesfully added to database.";
} else {
print_r($prepare->errorInfo());
}
}
Also make sure you change your database connection file to:
<?php
$dbhost = ""; //Enter MySQL server host
$dbuser = ""; //Enter MySQL database user
$dbpass = ""; //Enter MySQL database pass
$dbname = ""; //Enter MySQL database name
$pdo = new PDO("mysql:host=".$dbhost.";dbname=". $dbname, $dbuser, $dbpass);
?>
On a last note I should add that I didn't see any require database connection file inside your PHP code. I assume you simply didn't post this.
I have created a test form just to try to send my radio button value to mysql. I am having problems with it at the moment. The code below is just a test, I want the radio button to submit the value but it isn't.
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1">
<tr>
<td><form name="form1" method="post" action="insert_ac.php">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td colspan="3"><strong>TEST </strong></td>
</tr>
<tr>
<td width="71">Name</td>
<td width="6">:</td>
<td width="301"><input name="name" type="text" id="name"></td>
</tr>
<tr>
<td>Case</td>
<td>:</td>
<td><input name="case" type="radio" id="case1"> <input name="case" type="radio" id="case2"> <input name="case" type="radio" id="case3"></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><input name="email" type="text" id="email"></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
And here is the connection part of the database
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="123"; // Mysql password
$db_name="store"; // Database name
$tbl_name="test_mysql"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$name=$_POST['name'];
$case=$_POST['case'];
$email=$_POST['email'];
// Insert data into mysql
$sql="INSERT INTO $tbl_name(name, case, email)VALUES('$name', '$case', '$email')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
This is done by adding values to radio button input. For instance:
<form method="post">
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
<input type="submit">
</form>
You should start with closing all of your <input> tags with </input> or at least a slash at the end (like <input name="case" type="radio" id="case1"></input>).
You should set values to your radios (like this they always return 'on'), whereas the submit button needs neither name nor value.
EDIT:
Define a default radio with selected in yout input tag! If none is selected, there's no case getting transmitted and PHP will throw Undefined index: case when accessing $_POST['case'].
A good way to prevent such errors is to check if all necessary indices are set. You can do the following:
if(isset($_POST['name']) and isset($_POST['case']) and isset($_POST['email'])) { ... }
<!-- Once you have created Mysql connection and column in specified database table,-->
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "website";
// Create connection
$conn = mysqli_connect($servername, $username, $password,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
else{
echo "Connected successfully";}
$sql="INSERT INTO Registration(Name,FatherName,CNIC,FCNIC,Email,Password,Contact,Gender) VALUES ('$_POST[Name]','$_POST[FatherName]','$_POST[CNIC]','$_POST[FCNIC]','$_POST[Email]','$_POST[Password]','$_POST[Contact]','$_POST[Gender]')";
if (!mysqli_query($conn,$sql))
{
die('Error:'.mysqli_error($conn));
}
echo " & 1 record added";
mysqli_close($conn);
?>
<!--after that you just need to write this code and make sure to adjust this code because i'm posting some portion of my code."-->
<h4>Gender</h4> <input type="radio" value="Male" name="Gender"> Male
<input type="radio" value="Female" name="Gender" >Female <br><br>
<button type="Submit">Submit</button><br>
//This answer is for you.
I am trying to set up a feature very similar to a forum, where users can write chapters or stories (long sections of text). This text is then to be stored on mysql so that it can be recalled an read and commented on etc. This is all set up and works fine, however when a new line is typed by the user, it is not recognized. So the user may type -
This is para 1
This is para 2
But all that is displayed is -
This is para1This is para 2
I know that there are certain character is html and php such as or \n, but the people using the forum will not be savvy enough to do this. Is there a way that I can get this working automatically?
Below is the code for my add_topic.php
<?php
session_start();
$uname = $_SESSION['uname'];
$host="mysql.******************.co.uk"; // Host name
$username="**********"; // Mysql username
$password="************"; // Mysql password
$db_name="************_members"; // Database name
$tbl_name="forum_question"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get data that sent from form
$topic=$_POST['topic'];
$detail=$_POST['detail'];
$name=$_POST['username'];
$datetime=date("d/m/y h:i:s"); //create date time
$sql="INSERT INTO $tbl_name(topic, detail, name, datetime)VALUES('$topic', '$detail', '$name', '$datetime')";
$result=mysql_query($sql);
if($result){
echo "Successful<BR>";
echo "<a href=main_forum.php>View your topic</a>";
}
else {
echo "ERROR";
}
mysql_close();
?>
Currently the 'details' field on the database is set to MidText. I have also tried MidBlob but there is no change in the result.
The following is my create_topic.php code -
<?php
session_start();
$uname = $_SESSION['uname'];
?>
<table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form id="form1" name="form1" method="post" action="add_topic.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3" bgcolor="#E6E6E6"><strong>Create New Story</strong> </td>
</tr>
<tr>
<td width="14%"><strong>Title</strong></td>
<td width="2%">:</td>
<td width="84%"><input name="topic" type="text" id="topic" size="50" /></td>
</tr>
<tr>
<td valign="top"><strong>Story</strong></td>
<td valign="top">:</td>
<td><textarea maxlength="2000000" name="detail" cols="50" rows="30" id="detail"></textarea></td>
</tr>
<tr>
<td><strong>Username</strong></td>
<td>:</td>
<td><input name="username" value="<?php echo $uname; ?>" type="text" id="username" size="50" readonly></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Submit" /> <input type="reset" name="Submit2" value="Reset" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
I am an absolute beginner but I will try my best to make heads or tales of any advice that can be given. If you need anymore info please let me know.
Many thanks in advance.
Have you tried using nl2br before display? It will transform all the \n character to html <br/>.
See also the docs: http://php.net/manual/en/function.nl2br.php
Please try
$detail=htmlentities($_POST['detail']);
to get special HTML characters transformed in your database.
Hope that helps.
For further info go to http://php.net/manual/en/function.htmlentities.php
I have just started to work with php. I write a simple code in php to insert data in a table customer. I am using mssql database.
<?php
function InsertData()
{
$link = mssql_connect('db','123','test');
if (!$link || !mssql_select_db('php', $link))
{
die('Unable to connect or select database!');
}
$sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
$result = mysql_query($sql, $link);
if(!$result)
{
echo mysql_error();
exit;
}
// close the connection
mysql_free_result($result);
mysql_close();
echo "Data successfully inserted";
}
?>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td colspan="3" height="10" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%"> Name:</td>
<td width="60%"><INPUT type="text" name="txtName" id="txtName" Width="200px" MaxLength="30" /> </td>
</tr>
<tr>
<td colspan="3" height="12" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%"> Company Website:</td>
<td width="60%"><INPUT type="text" name="txtWebsite" id="txtWebsite" width="200px" MaxLength="200" /> </td>
</tr>
<tr>
<td > </td>
<td > <input type="button" value="submit" id="imgBtnSubmit" click="InsertData()"/> </td>
</tr>
</table>
I have written above code to insert data into the table and I am calling InsertData function on onClick event of submit button but on clicking button data is not getting inserted into the table. Please anyone tell me where is the problem in this code.
There are a few problems with your code.
You're missing the <form> as pointed out by Tudor Constantin.
The other problem is that you can't use the onclick event of an element to trigger PHP code as you're done above. The onclick event is for JavaScript (or other client side scripting languages like VBScript).
Additionally, make sure that you use the functions that start with mssql and not mysql if you use Microsoft SQL Server. The functions are not interchangeable.
Here's a short example:
<?php
// The request method is POST.
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
// Connect to the database
$link = mssql_connect('db','123','test');
// Do more stuff with the database.
}
?>
<form method="POST" action="/path/to/this/file.php">
<input type="text" name="example" />
<input type="submit" value="Send" />
</form>
When you click the "Send" button, the form will be POSTed to /path/to/this/file.php. By checking that the request method is "POST", you can then connect to the database and insert records accordingly.
Checking for $_SERVER['REQUEST_METHOD'] is one of many ways you can do this. You could also check that a value for an particular input was set using if ( ! empty($_REQUEST['input_name']) ) { ... }.
As the previous answer states, you don't actually have submission logic. What's at least equally important is that you, by your own admission, do not have a MySQL server. MySQL and MS-SQL are different and not at all equivalent. You can't use PHP MySQL commands or the MySQL extension to talk to MS-SQL.
You're using MS-SQL functions here:
$link = mssql_connect('db','123','test');
if (!$link || !mssql_select_db('php', $link))
{
die('Unable to connect or select database!');
}
and then MySQL here:
$sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
$result = mysql_query($sql, $link);
if(!$result)
{
echo mysql_error();
exit;
}
// close the connection
mysql_free_result($result);
mysql_close();
echo "Data successfully inserted";
...and, as yet another answer states, you're trying to use Javascript to call a PHP function.
You therefore have two three problems - well, technically one problem. I suggest you read a FAQ on MS-SQL in PHP at the very least, and ideally complete Javascript and PHP tutorials. There is no way that we can provide an answer that you can use short of writing your program for you, as you - and I swear I'm not being unpleasant here, I know you're doing your best - just don't have the knowhow to put it together yet. Google is your friend here. Good luck.
As many have already mentioned there are a few errors in your code. My solution to your question offers a different approach.
Rather than calling the InsertData() method you can do something else in the one php document.
This is done by using an if/else statement, assigning 'submit' to the name value of the submit button as well as the special PHP variable $_SERVER['PHP_SELF'].
First, the server checks if the form has been submitted.
When the page is first loaded this will return false and the form is displayed for them to fill out
When the user clicks the submit button the form reloads the page and runs the PHP script again. This time the if statement returns true as the form HAS been submitted so it executes the part of the script that inserts the data in MSSQL and displays the successful message.
Check out the code below:
<?php
if (isset($_POST['submit'])){
//connect to the database
$link = mssql_connect('db','123','test');
//display error if database cannot be accessed
if (!$link || !mssql_select_db('php', $link))
{
die('Unable to connect or select database!');
}
//assign form input to variables
$txtName = $_POST['txtName'];
$txtWebsite = $_POST['txtWebsite'];
//SQL query to insert variables above into table
$sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
$result = mssql_query($sql, $link);
//if the query cant be executed
if(!$result)
{
echo mssql_error();
exit;
}
// close the connection
mssql_free_result($result);
mssql_close();
echo "Data successfully inserted";
}
else { ?>
<form name="input" action="$_SERVER['PHP_SELF']" method="POST">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td colspan="3" height="10" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%">Name:</td>
<td width="60%"><INPUT type="text" name="txtName" id="txtName" Width="200px" MaxLength="30" /> </td>
</tr>
<tr>
<td>Company Website:</td>
<td><INPUT type="text" name="txtWebsite" id="txtWebsite" width="200px" MaxLength="200" /></td>
</tr>
<tr>
<td><input type="button" name="submit" value="submit" /></td>
</tr>
</table>
</form>
<?php } ?>
Give that a try. There's some great PHP tutorials that go over the fundamentals here:
http://devzone.zend.com/article/627
Hope that all helped.
It looks like you don't have a <form> in your page - the data is not getting to your server.
Also, you are not reading the input anywhere - how do you fill your $txtName and $txtWebsite with meaningful values?
Also, InsertData is a PHP function, which is executed on the server side - your HTML part is interpreted on the client side (in the browser). You can't call that function there.
Try with this:
<?php
function InsertData()
{
$link = mssql_connect('db','123','test');
if (!$link || !mssql_select_db('php', $link))
{
die('Unable to connect or select database!');
}
$txtName = $_REQUEST['txtName'];
$txtWebsite = $_REQUEST['txtWebsite'];
$sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
$result = mssql_query($sql, $link);
if(!$result)
{
echo mssql_error();
exit;
}
// close the connection
mssql_free_result($result);
mssql_close();
echo "Data successfully inserted";
}
if ($_REQUEST['txtName'] > ''){
InsertData();
}
?>
<form name="input" action="this_file_name.php" method="get">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td colspan="3" height="10" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%"> Name:</td>
<td width="60%"><INPUT type="text" name="txtName" id="txtName" Width="200px" MaxLength="30" /> </td>
</tr>
<tr>
<td colspan="3" height="12" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%"> Company Website:</td>
<td width="60%"><INPUT type="text" name="txtWebsite" id="txtWebsite" width="200px" MaxLength="200" /> </td>
</tr>
<tr>
<td > </td>
<td > <input type="button" value="submit" id="imgBtnSubmit" /> </td>
</tr>
</table>
</form>