I have a form in HTML, but it's not setup like normal I guess. I'll post the code form the HTML (PHP) file and the php to send it to the db.
<form action="upload.php" method="POST">
<!-- Name input-->
<div class="form-group">
<label class="control-label" for="name">Name</label>
<div class="">
<input id="name" name="name" placeholder="First and Last Name" class="form-control input-md" type="text" required>
</div>
</div>
<div class="form-group">
<label class=" control-label" for="supportingDoc">Upload Supporting Documentation</label>
<div class="">
<input id="supportingDoc" name="supportingDoc" class="input-file" type="file" style="margin-top: .5em; margin-left: 4em;">
</div>
</div>
<hr>
<!-- Submit -->
<div class="form-group">
<label class="control-label" for="submit"></label>
<div class="">
<button value="Submit" type="submit" id="submit" name="submit" class="btn btn-danger" style="border-radius: 25px;">Submit</button>
</div>
</div>
</form>
Here is my SQL/PHP
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$con = mysqli_connect("localhost","xxx","xxx","xxx");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_REQUEST['name'])){
// set variables
$name = mysql_real_escape_string($_POST['name']);
$supportingDoc = mysql_real_escape_string($_POST['supportingDoc']);
$sql = "INSERT INTO `tablew` (name, supportingDoc) VALUES ('$name', '$supportingDoc')";
$result = mysqli_query($con,$sql);
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
printf("New record created successfully");
} else {
echo "Error: " . $sql . "<br>" . $con->error;
printf("Error: " . $sql . "<br>" . $con->error);
}
$con->close();
}
?>
I've tried all sorts of variations and nothing is showing in phpmyadmin. I've even replicated from a previous site I created and it still didn't work lol.
I see that there are variables for the login info and still put it in the mysqli, but I've been at this one thing for about 8 hours now and am out of juice, so hopefully someone sees what I messed up on.
Thanks in advance for any help everyone.
===========================================================================
UPDATE:
I made all the changes mentioned above and now get this:
Warning: mysqli_connect(): (HY000/1049): Unknown database
I can see the database in phpmyadmin and Sequel Pro. I've also made sure to set the password and login to 'root'. My code is as follows for login:
$con = mysqli_connect("localhost","root","root","epboarding");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
and this is my POST:
if (isset($_REQUEST['submit'])){
// set variables
$name = mysqli_real_escape_string($con, $_POST['name']);
$sql = "INSERT INTO `wos` (name) VALUES ('$name')";
$result = mysqli_query($con,$sql);
Following issues can be there:
Uploading error. Use enctype="multipart/form-data" in form tag.
Correct Mysql_connect details i.e. Username, Password, Dbname.
mysql_real_escape_string is depricated. Use mysqli.
Recheck your column names i.e. name, supportingDoc.
Your html code wrong. Whenever you want to use input type file, you need to put <form> tag to <form enctype="multipart/form-data">. If you re not declaring the enctype, then the PHP cannot read the file.
you have to put
<form enctype="multipart/form-data">
when uploading file . correct your html.
Try This
The issue is after clicked on submit button it's not hitting the (isset($_REQUEST['name']))
Change it
if (isset($_REQUEST['submit'])){ //code here}
because you button name is submit.
Use SQL injection like
$con->real_escape_string($_POST['name']);
for the unknown database error. I simply went to operations in phpmyadmin and changed the name of the database and it worked. give it a try if you haven't fixed the problem yet.
in addition to #tbi
answer
Check php.ini for max post size it cause the POST request to fail if the size exceeds the size set in php.ini
post_max_size=20M
upload_max_filesize=20M
check your SQL connection and your permissions on the DB
use enctype="multipart/form-data" in your form only when you need to upload files (for security reasons)
finally, don't forget to bind your post params to prevent SQL-Injection
Params Binding
If you are using a default account on a local installation, then your connection code will probably look like this:
<?php $con = mysqli_connect('localhost','root','');
mysqli_select_db('epboarding', $con); ?>
use enctype="multipart/form-data" in form tag when you use file type.
<form name="" method="POST" action="" enctype="multipart/form-data">
3.change the following line
if (isset($_REQUEST['name'])){
to
if (isset($_REQUEST['submit'])){
correct the syntax when post data like mysql to mysqli.
From the PhpMyAdmin screenshot, it looks like the database is running on port 8889, meaning you would need:
$con = mysqli_connect("localhost","xxx","xxx","xxx", 8889);
In addition to what the others have said, I thought I'd provide a tidied script and some (hopefully) useful resource for you other issues.
http://php.net/manual/en/mysqli.construct.php
What's wrong with using $_REQUEST[]?
https://www.w3schools.com/sql/sql_injection.asp
As for your unknown database error this is either your database doesn't exist, is incorrectly named in your PHP script or is unavailable through localhost.
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ( $conn->connect_error ) {
echo "Failed to connect to MySQL: " . $conn->connect_error;
}
// Check if values are set with post rather than request, as this is deprecated and can output unexpected results
if ( isset( $_POST['name'] ) ) {
// Set variables
$name = $_POST['name'];
$supportingDoc = $_POST['supportingDoc'];
// Prepare a statement and bind parameters to prevent sql injection
$stmt = $conn->prepare( "INSERT INTO `tablew` (name, supportingDoc) VALUES (?, ?)" );
$stmt->bind_param( 'sb', $name, $supportingDoc );
if ( $stmt->execute() ) {
echo "New record created successfully";
printf( "New record created successfully" );
} else {
echo "Error: " . $stmt->error;
printf( "Error: " . $stmt->error );
}
$stmt->close();
$conn->close();
}
Related
Whenever I tried to insert data to the table of database it keeps echoing "Connection successful" from connection.phpThe connection successful in my insert.php file
insert.php code
<?php
include_once("connection.php");
if(isset($_POST['Add'])){
$productCat = $_POST['category'];
$insertQuery = $pdo->prepare("INSERT INTO products_tbl (productCategory) VALUES (:ucategory)");
$insertQuery->bindParam(':ucategory',$productCat);
$insertQuery->execute();
echo "<script>alert('Successfully Register')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
?>
connection code
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "Ecommercedb";
try{
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection success";
} catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
?>
forms
<form action="insert.php" method="post">
<label for="">Product Category</label>
<input type="text" name="category" id="" placeholder="Category">
<input type="submit" value="Submit" class="btn" name="Add">
</form>
I tried removing the echo enter image description heresince it wasn't needed but it only lead to
HTTP:500 error.
I have also checked the connection and it is successful.
I expected there would be an alert saying it is successfully inserted but instead I keep getting the connection success from my connection.php
It looks like your code is working as intended, and the issue is likely related to the way you are submitting your form. The "Connection successful" message is being printed because your connection to the database is working, but the form data is not being passed to the insert.php script.
Make sure that you are correctly specifying the action attribute of the form element, and that the method is set to "post". Also, check that the name attributes of the form elements match the names of the variables in the insert.php script.
Additionally, you can try adding some debugging statements to the insert.php script, such as var_dump($_POST) or echo $productCat to check if the values are being passed to the script correctly.
I'm attempting to create a page, where I can search for case files from my database, however, I can't get my code to work.
I already have pages showing all content of the database and where I can add new content.
I've read guides, tutorials and questions on stackoverflow, but can't find an answer on how to proceed.
I have the following php code in searchcasescript.php
<?php
$servername = "localhost";
$username = "test";
$password = "";
$dbname = "test";
$conn = mysqli_connect($servername, $username, $password, $dbname) or
die("connection failed: " . mysqli_connect_error());
mysqli_select_db($conn, $dbname) or die("something went wrong");
if(isset($_GET["form_submit"]))
{
$journalnummer =$_GET["journalnummer"];
$stmt = $conn->prepare("select * from testcases where journalnummer=? ");
$stmt->bind_param("s",$journalnummer);
$stmt->execute();
$val = $stmt->get_result();
$row_count= $val->num_rows;
if($row_count >0)
{
$result =$val->fetch_assoc();
print_r($result);
}
else{
echo "wrong number";
}
$stmt->close();
$conn->close();
}
?>
and my html:
<div class="container-fluid">
<div class="form-group">
<form action="searchcasescript.php" method="post">
<label for="journalnummer">Journalnummer:</label>
<input type="text" name="journal" class="form-control" required>
<div class="form-group"> <br>
<input type="submit" name="form_submit" class="btn btn-basic" value="Søg">
</form>
I've had different results depending on my changes to the php, but currently I'm getting nothing. Pressing search opens a new, blank page.
What I would like to end up with was being able to enter full or part of a case number and the search results being displayed on the same or a new page.
Can anyone point me in the right direction to read more about this and/or where to proceed with my code?
And apologies, if I've somehow missed the answer in one of the questions here.
UPDATED WITH "LIKE":
$stmt = $conn->prepare("SELECT * FROM straffesager WHERE journalnummer LIKE ?");
$stmt->bind_param("s", '%' . $journal . '%');
$journalnummer =$_GET["journalnummer"];
Your looking for journalnummer but your input has a name of journal
<input type="text" name="journal" class="form-control" required>
$_POST['journal'];
This is what should contain the number .
I'm trying to confirm if a user submitted valid credentials.
HTML
<form action="assets/php/account/login_user.php" method="post" id="login" class="center">
<div id="register_errorloc"></div>
<div class="form-group">
<input type="text" name="login_username" id="login_username" class="form-control" placeholder="Username" />
</div>
<div class="form-group">
<input type="password" name="login_password" id="login_password" class="form-control" placeholder="Password" />
</div>
<div class="form-group">
<input type="submit" value="login" id="submit_login" class="btn btn-success form-control"/>
</div>
</form>
PHP
$username = trim($_POST['login_username']);
$password = hash('sha512',trim($_POST['login_password']));
//to check if values are correct by myself
echo '<br>' . $username . '<br>' . $password . '<br>';
include_once '../../../assets/php/DB/DBConnect.php';
//check if valid credentials are entered
$stmt = $conn->prepare("SELECT * FROM tbl_users WHERE username = ?");
echo $stmt->bind_param('s', $username);
echo $stmt->execute();
echo $stmt->store_result();
if($stmt->num_rows == 1){
echo 'Good Creds';
}else{
echo 'Bad Creds';
}
When I'm doing this it always shows 0 results. When I change the querystring to
$stmt = $conn->prepare('SELECT * FROM tbl_users WHERE username = "abc"');
I get the result I'm looking for. I'm confused because I'm using the same approach on a different page and it's working like a charm.
Screenshots
Login form
Submitted form
Row I'm looking for
Edit: Added all code.
Edit2: Added screenshots
Edit3: Added Form HTML
Edit4:
Nothing is wrong with the form submit. When I'm hardcoding the variable like this:
$username ='abc';
It still doesn't work
I'm sorry but you posted screenshots that don't help us.
In order to avoid further commenting, am submitting the following.
Your form and its related elements may be failing and require a POST method and that name attributes exist for each of them.
I.e.:
<form method="post" action="???">
<input type="text" name="login_username">
...
Edit:
Try the following, comments are getting too extensive:
$check = $conn->prepare("SELECT * FROM tbl_users WHERE username=?");
$check->bind_param("s", $username);
$check->execute();
$check->store_result();
$row_chqry = $check->num_rows;
if($row_chqry > 0 ) {
echo "Exists";
$check->close();
$conn->close();
}
Edit #2:
OP posted an answer stating that they were using the same variable for their db connection.
Something I would have spotted right away and causing a conflict, had full code been posted. I've seen that happen quite a few times before, and remember posting answers for them too. As to where they are exactly, it would take some time for me to find them; but I do remember posting answers for related questions.
Oh well, problem solved.
Solutions:
Use a different variable for your username(s).
Use unique variables.
I finally found the error:
When connecting to my DB I use:
$servername = "";
$username = "";
$password = "";
$db = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
In my submission script I also use $username. Including the DBconnection file caused my local variable ($username that I get from the form) to be overwritten with the username found in the DBconnect.
Okay, I've looked everywhere. To begin with I have a form, a newsletter, that users enter their email into. Once they hit submit it checks a php form that takes that email and inputs it into an SQL database that stores the email. The problem is I get this error when submitting the form
Error: INSERT INTO emails (email) VALUES (random#yahoo.com)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#yahoo.com)' at line 2
No idea why it wont put it into the database. The form code is
<section>
<div class="mockup-content">
<div class="morph-button morph-button-inflow morph-button-inflow-1">
<button type="button"><span>Subscribe to our Newsletter</span></button>
<div class="morph-content">
<div>
<div class="content-style-form content-style-form-4">
<h2 class="morph-clone">Subscribe to our Newsletter</h2>
<form action="scripts/mailer.php" method="post">
<p><input type="text" class="button" id="email" name="email" placeholder="NAME#EXAMPLE.COM">
<div>We promise, we won't send you any spam. Just love.</div>
<input type="submit" class="button" id="submit" value="SIGN UP"></p>
</form>
</div>
</div>
</div>
</div><!-- morph-button -->
</div>
</section>
This is just the html data for the form, the php data is
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mysql";
$email = ($_POST["email"]);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO emails (email)
VALUES ($email)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Can anyone explaine why this is?
You should use a tick (') when binding variables in a query:
$sql = "INSERT INTO emails (email) VALUES ('$email')";
It is okay not to use tick when the value of your variable you are trying to bind is an int.
The email is in varchar datatype . you need to put quotes on it
$sql = "INSERT INTO emails (email) VALUES ('".$email."')";
im trying out some code by my own. I just started to learn PHP & mysql. Could anyone tell me where is the mistake? I got a error when processing the query.
My db is set like in the code.
Db name: sweepstakes
Table name: alfa
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "sweepstakes";
$db = mysqli_connect($dbhost,$dbuser,$dbpass, $dbname);
if(mysqli_connect_errno()){
die("Database connection failed: " .
mysqli_connect_errno() .
" (" . mysqli_connect_errno() . ")"
);
}
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Submit'
&& !empty($_POST['name'])
&& !empty($_POST['description'])
&& !empty($_POST['adress'])) {
$name = $_POST['name'];
$desc = $_POST['description'];
$adress = $_POST['adress'];
$query = "INSERT INTO alfa (name, description, adress) VALUES ('$name', '$desc', '$adress')";
$result = mysqli_query($db, $query);
if($result){
}else{
die("Database query failed." . mysql_error() . " " . mysqli_connect_error($db));
}
} else { echo "Empty!";
}
?>
<form method="post" action="index.php">
<fieldset>
<legend>New Sweepstakes</legend>
<label>Name: </br>
<input type="text" name="name" maxlength="150" />
</label> </br>
<label>Description:</br>
<textarea name="description" cols="45" rows="10"></textarea>
</label> </br>
<label>Adress:</br>
<input type="text" name="adress" maxlength="1080" />
</label> </br>
<input type="submit" name="submit" value="Submit" />
</fieldset>
</form>
You're mixing mysql and mysqli functions. Stick with mysqli, mysql is deprecated (don't use it).
In case you didn't spot it: mysql_error() should be mysqli_error()
In addition to checking what Halcyon writes ( using mysqli_error() ), I would also check the query string itself. Just echo out $query right after it's built (the $query = "INSERT..." line) and when running the script look to see if the output matches what you expect to happen, ie that you see something like INSERT INTO alfa (name, description, adress) VALUES ('fred', 'blonde dude', 'Anywhere 32B'). If anything looks out of place (like maybe you have a ' or " in the inputed data and it's screwing up the string output), fix it and try again.
echo and print and print_r()are your friends when doing detective work on new code to see what is the output expected.
(edit)
After reading your update with Halcyon, you should probably check how your auto-incremented field is set up. If, for example, you've been tinkering with this for a while but only set the auto-increment field to INT(2), you might have run out of space for numbers (can only go up to 99 with INT(2)). Increase it to INT(11) or something similar, empty the table, and try again. You can also try ALTER TABLEtable_nameAUTO_INCREMENT = 1 to reset the auto numbering.