How doesnt my php code connect to the database..using Xampp - php

First forgive me if the code is not in an organized manner, I have tried to insert code in a neat manner but by the time I fix it, the system times out, so I cant post and have to do it all over again..so this time I am not going to adjust the code.. just copy past it into forum
I created a from called product_insert.html.. and a php script called product_insert.php. They are both located in a sub folder called Final exam, in the htdoc folder of xampp.
After entering data into form, the next screen basically shows me the script of the product_insert.php. I cannot figure out why it does not make the connection. Also the database is called final_exam.
i have edited my code to the following and i am still getting errors
<html>
<head></head>
<body>
<?php
mysql_connect("localhost", "root", "Final exam")
or die(mysql_error());
//echo "We have successfully connect to our DB.<br/>";
mysql_select_db( "final_exam") or die(mysql_error());
//echo "Successfully opened DB.<br/>";
//pull values from the URL and put them each in a variable
$Description = addslashes($_GET["Description"]);
$Quantity = addslashes($_GET["Quantity"]);
$Price = addslashes($_GET["Price"]);
$Vend_id = addslashes($_GET["Vend_id"]);
if($Description && $Quantity && $Price && $Vend_id)
{
echo "test1";
}
else
{
echo "test2";
}
if(isset($Description) && !empty($Description)
&& isset($Quantity) && !empty($Quantity)
&& isset($Price) && !empty($Price)
&& isset($Vend_id) && !empty($Vend_id))
{
$SQLstring = "INSERT INTO student (id, first_name,last_name,address, e_mail,
gpa)
VALUES (NULL, '$first', '$last', '$address', '$email', 0.0)";
$QueryResult = #mysqli_query($DBConnect, $SQLstring)
Or die("Insert Broke!!!");
echo "insert complete";
}
else
{
echo "You are missing some values...Please press the back button and retry!";
}
//redirect back to our list page since the insert worked
header("location: db_connect.php");
?>{/PHP]
<!--Insert Complete: click here to go back to the
list!-->
</body>
</html>
i have edited my code to the following and i am still getting errors
<html>
<head></head>
<body>
<?php
$host = "localhost"; // change this as required
$username = "root"; // change this as required
$password = "password"; // change this as required
$db = "final_exam"; // your DB
$DBConnect=mysql_connect("localhost", "root", "password")
or die("Could Not Connect");
//echo "We have successfully connect to our DB.<br/>";
mysql_select_db( "final_exam")
or die(mysql_error());
//echo "Successfully opened DB.<br/>";
//pull values from the URL and put them each in a variable
$Description = addslashes($_GET["Description"]);
$Quantity = addslashes($_GET["Quantity"]);
$Price = addslashes($_GET["Price"]);
$Vend_id = addslashes($_GET["Vend_id"]);
if($Description && $Quantity && $Price && $Vend_id)
{
echo "test1";
}
else
{
echo "test2";
}
if(isset($Description) && !empty($Description)
&& isset($Quantity) && !empty($Quantity)
&& isset($Price) && !empty($Price)
&& isset($Vend_id) && !empty($Vend_id))
{
$SQLstring = "INSERT INTO student (id,
VALUES ('$Description', '$Quantity', '$Price', '$Vend_id')";
$QueryResult = #mysql_query($DBConnect, $SQLstring)
Or die("Insert Broke!!!");
echo "insert complete";
}
else
{
echo "You are missing some values...Please press the back
button and retry!";
}
//redirect back to our list page since the insert worked
header("location: product_list.php");
?>
<a a href="product_insert.html">Click here</a> to go back to the list!-->
</body>
</html>

mysql_connect('localhost', 'mysql_user', 'mysql_password');
You are missing either user or password in your connection string.Instead you use the db name.
Also you are mixing mysqli and mysql functions.

Related

Echo is not showing up in api

I'm trying to make an api for my iOS application by sending POST http requests to my api.php. I'm testing it right now, but my echo is not showing up? The only moment my echo works is when I delete everything and just write echo 'Test';.
Here is my code:
<?php
$user = '';
$pass = '';
$dbh = new PDO('mysql:host=localhost;dbname=iOS', $user, $pass);
if(isset($_POST['status']) && $_POST['status'] == "login")){
// Login stuff
}else if(isset($_POST['status']) && $_POST['status'] == "registreren")){
//Register stuff
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['email']))){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "INSERT INTO `user` (username, password, email) VALUES ('$username', '$password', '$email')";
if($dbh->execute($sql)){
echo 'Did it';
}else{
echo 'Nop';
}
}
}else{
echo 'Something is wrong';
}
$dbh = null; // PDO sluiten
?>
I'm not so good at php, but in my case there should always return 'Something is wrong' when accessing the api.php by URL because I don't send any POST requests with it.
There are several syntax errors which might prevent your code from executing correctly. In every if-statement, there is an additional bracket.
Eg: if(isset($_POST['status']) && $_POST['status'] == "registreren")) should be replaced by if(isset($_POST['status']) && $_POST['status'] == "registreren") (note that the last bracket is missing).
Remove the additional brackets at the end of every if-statement in your code and it might be fine.

Validating form then submitting to database with php

I've been reluctant to come back to Stackoverflow to ask this question. It's definitely been asked many times over, but every answer hasn't been able to fix the problem. I've attempted the Header() fix: https://stackoverflow.com/a/18820079/3831297 to no avail and now I have been trying to instead just validate and submit from the same page.
When I was using the Header redirect nothing would happen, no redirect to the next page while also not giving any errors for a reason. Which leaves me with the method below.. A mess of code that I've spent 60+ hours on trying to get to work from answers found on here as well as other websites.
What I've been trying to do with this version is validate with:
if(empty()) {
display error
}else{
variable = true
if(variable = true){
post to database
}
I apologize for the repeated question as well as for my complete lack of knowledge. I am learning as I go with these hands-on projects.
<?php
if (mysqli_connect_errno()) {
echo "Connection to the database failed! Submitting a story will not work! Try again in a few minutes!" . mysqli_connect_error();
}else{
echo "<br>";
echo "<h4>" . "Database connected successfully... It is safe to submit a story!" . "</h4>";
}
$TitleErr = $StoryErr = $AuthorErr = $DateErr = "";
$Title = $Story = $Author = $Date = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Title"])) {
$TitleErr = "Title is required!";
}else{
$valid1 == true;
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Story"])) {
$StoryErr = "Story is required!";
}else{
$valid2 == true;
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Author"])) {
$AuthorErr = "Author is required!";
}else{
$valid3 == true;
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["Date"])) {
$DateErr = "Date is required!";
}else{
$valid4 == true;
}
}
if ($valid1 = $valid2 = $valid3 = $valid4 = true) {
$Title = mysqli_real_escape_string($con, $_POST['Title']);
$Date = mysqli_real_escape_string($con, $_POST['Date']);
$Author = mysqli_real_escape_string($con, $_POST['Author']);
$Story = mysqli_real_escape_string($con, $_POST['Story']);
$sql="INSERT INTO Moderate (Title, Story, Author, Date)
VALUES ('$Title', '$Story', '$Author', '$Date')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}else{
echo "<br>";
echo "Story submitted for moderation!";
}
}
mysqli_close($con);
//Insert into database
//$sql="INSERT INTO Moderate (Title, Story, Author, Date)
//VALUES ('$Title', '$Story', '$Author', '$Date')";
?>
<h2>Submit News</h2>
<?php// echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<span class="error">* <?php echo $TitleErr;?></span>
Title: <input type="text" name="Title">
<span class="error">* <?php echo $AuthorErr;?></span>
Author: <input type="text" name="Author">
<span class="error">* <?php echo $DateErr;?></span>
Date: <input type="date" name="Date">
<input type="submit"><br>
<span class="error">* <?php echo $StoryErr;?></span>
Story: <br><textarea type="textarea" rows="40" cols="100" name="Story" method="post"></textarea>
</form>
</div>
<?php
//// escape variables for security
//$Title = mysqli_real_escape_string($con, $_POST['Title']);
//$Story = mysqli_real_escape_string($con, $_POST['Story']);
//$Author = mysqli_real_escape_string($con, $_POST['Author']);
//$Date = mysqli_real_escape_string($con, $_POST['Date']);
//Insert into database
?>
I'm going to hazard an answer. Main thing I see is you are using == as assignment and = as comparison. This is backwards.
$valid4 == true; should be $valid4 = true;
if ($valid1 = $valid2 = $valid3 = $valid4 = true) should be if ($valid1 == $valid2 == $valid3 == $valid4 == true) or not really, since it actually has to be:
if ($valid1==true && $valid2==true && $valid3==true && $valid4==true)
With assignment you can stack up the operator, but with boolean comparison, combine the compares with and (&&).
Just some advise, don't make pages submit to themselves. Make a separate page to handle the form from the one that displays the form. That way if you ever want to upgrade to using Ajax, its much easier. Also after doing a db update like this you always need to redirect to another page to prevent double submit (unless using ajax). The page doing the db update should not print anything out but just do the db update and redirect, unless there's a validation error.
Change your PHP to this:
if (isset($_POST['Title'],$_POST['Date'], $_POST['Author'], $_POST['Story'] )){
$con = mysqli_connect("localhost", "my_user", "my_password", "db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$title = $_POST['Title'];
$date = $_POST['Date'];
$author = $_POST['Author'];
$story = $_POST['Story'];
$query = "INSERT INTO Moderate (Title, Story, Author, Date)
VALUES (?, ?, ?, ?)"
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, $query)) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ssss", $city);
/* execute query */
mysqli_stmt_execute($stmt);
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($con);
}

mysqli real escape string issues

How can I use mysqli_real_escape_string in my script to prevent SQL injection. I was working on some code and asking some questions here and I was advised to use mysqli_real_escape_string instead of mysql_real_escape_string, the problem is my code does not make a connection until after the variables I want to secure. It was suggested that I should used prepared statements instead but after some searching http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php I feel more confused. Right now the code if doing exactly what it is not supposed to do, it is inserting empty values/rows into my table, which from my reading is probably because of the use of mysqli_real_escaape_string
Any thoughts or help is appreciated, I am so frustrated and confused but still trying to learn. Here is the code:
<?php
//Form fields passed to variables
$manu = mysqli_real_escape_string($_POST['inputManu']);
$model = mysqli_real_escape_string($_POST['inputModel']);
$desc = mysqli_real_escape_string($_POST['inputDesc']);
//Connect to database using $conn
include ('connection.php');
//Insert record into table
$sql = "INSERT INTO gear (`id`,`manu`,`model`,`desc`)
VALUES (NULL,'$manu','$model','$desc')";
//Check for empty fields
if (isset($_POST['submit']))
{
foreach($_POST as $val)
{
if(trim($val) == '' || empty($val))
{
die('Error: ' . mysqli_error());
echo "Please complete all form fields!";
echo "<meta http-equiv='Refresh' content='3; URL=../add.php'>";
}
}
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
else
{
//echo "1 record added";
echo "Success, You added the ".$manu." ".$model."";
echo "<meta http-equiv='Refresh' content='3; URL=../index.php'>";
}
}
else
{
echo "some error";
}
mysqli_close($conn);
?>
<?php
//Connect to database using $conn
include ('connection.php');
//Form fields passed to variables
$manu = mysqli_real_escape_string($conn, $_POST['inputManu']);
$model = mysqli_real_escape_string($conn, $_POST['inputModel']);
$desc = mysqli_real_escape_string($conn, $_POST['inputDesc']);
Hope Below code will help you.
<?php
//Connect to database using $conn
/*in connection.php
$link = mysqli_connect("localhost", "root", "", "test");
*/
include ('connection.php');
//Check for empty fields
if (isset($_POST['submit']))
{
//Form fields passed to variables
$manu = mysqli_real_escape_string($link,$_POST['inputManu']);
$model = mysqli_real_escape_string($link,$_POST['inputModel']);
$desc = mysqli_real_escape_string($link,$_POST['inputDesc']);
if($manu!='' && $model!="" && $desc!="")
{
//Insert record into table
$sql = "INSERT INTO gear (`id`,`manu`,`model`,`desc`)
VALUES (NULL,'$manu','$model','$desc')";
$r=mysqli_query($link,$sql) ;
//echo "1 record added";
if($r)
{
echo "Success, You added the ".$manu." ".$model."";
// echo "<meta http-equiv='Refresh' content='3; URL=../index.php'>";
}
}
else
{
echo "Please complete all form fields!";
}
}
?>

PHP Registration Script, Inserting to Database not working

I have an issue with my PHP code for a registration form on my website. Some of the code doesn't get executed when the form is submitted.
if ($fnameError = "" && $emailError = "" && $userError = "" && $passError = "" && $cpassError = "" && $tickError = "") {
$con = mysqli_connect("localhost","root","","login")or die("Can't connect to database");
$user = $_POST['user'];
$pass = $_POST['pass'];
$name = $_POST['fname'];
$email = $_POST['email'];
$pwd = crypt('$pass', '$user');
$pwd = md5($pwd);
$tblname = "users";
$flp="INSERT INTO $tblname (Name, Username, Password, Email Address)
VALUES
('$name','$user','$pass','$email')";
$res = mysqli_query($con, $flp)or die("Can't insert to table");
if ($res) {
$complete = "Registered successfully please log in to continue";
} else {
echo "error";
}
}
Everything works fine until it gets to the line starting $flp="INSERT INTO...
Can anyone assist in helping me debug this code, also, please don't link to already written code I want to be able to use this code.
EDIT:
I changed a line to purposely cause an error so I know PHP is reading the line and it does give me the syntax error for the line starting $res=mysqli_...
"Parse error: syntax error, unexpected '$res' (T_VARIABLE) in C:\XamppNew\htdocs\site\regusr.php on line 85"
I removed the semi-colon at the end of the Insert line just to get the error.
EDIT:
I've managed to isolate the problem to the start of the if statement. It seems to be that the line doesn't treat each error as having no content. However, if the error exists it will be displayed on the page next to the form and no such error gets displayed.
Try this:
<?php
//if ($fnameError = "" && $emailError = "" && $userError = "" && $passError = "" && $cpassError = "" && $tickError = "")
//{
// Connect to DB
$mysqli = new mysqli("localhost", "root", "", "login");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// Parse Input
$user = $mysqli->real_escape_string($_POST['user']);
$pass = $mysqli->real_escape_string($_POST['pass']);
$pwd = md5(crypt('$pass', '$user'));
$name = $mysqli->real_escape_string($_POST['fname']);
$email = $mysqli->real_escape_string($_POST['email']);
// Insert Record
if ($mysqli->query("INSERT INTO users (`Name`, `Username`, `Password`, `Email Address`) VALUES ('$name', '$user', '$pwd', '$email')")) {
printf ("New user has id %d.\n", $mysqli->insert_id);
} else {
printf("Failed to insert row: %s\n", $mysqli->error);
}
// Close DB Connection
$mysqli->close();
//}
?>
You need to quote (with backticks) your column name Email Address since it has a space in it.
Use backticks in Email Address field because it has space.
$flp="INSERT INTO $tblname (`Name`, `Username`, `Password`, `Email Address`)
Try this ..........
$flp="INSERT INTO $tblname (Name, Username, Password, EmailAddress)
VALUES
('".$name."','".$user."','".$pass."','".$email."')";

Issues with undefined index in php/mysql

I hope that I describe my problem properly. I have created a database for a cafeteria. This has the following tables: orders, members ISA manager and servers, products and categories. In the table orders I should insert features such as title,quantity,datetime,sum and user name of the corresponding server. I've managed to do so via php in my files posted before in this forum (follow the link: Insert data from textbox and checkbox into database ).
The web environment so far is consisted of :
a)index.php, members.php (these files are responsible for the login and the authentication of any kind of user, either the administrator or serves.
b)addorder_form.php and addorder.php as far the order form and the insert of the order details in database.
I cannot make my system print the username of each server for each order.
I tried something like this but I 've got the error of undefined index username :
<?php
session_start();
include_once("buzzcafe_fns.php");
include_once("members.php");
do_html_header("");
$conn = mysql_connect("localhost", "root", "");
$db=mysql_select_db("buzzcafe" ,$conn);
db_connect();
if (isset($_SESSION['username']){
if (isset($_POST['products'])) {
if (isset($_POST['quantity'])) {
foreach($_POST['products'] as $key => $products){
$quantity = isset($_POST['quantity'][$key])? $_POST['quantity'][$key]:'Not selected';
date_default_timezone_set('Europe/Athens');
$date = date('Y-m-d H:i:s');
$message[] = $products.' - x'.$quantity;
$insertOrder = mysql_query("INSERT INTO orders (datetime,title,quantity,username) VALUES('".$date."','".$products."','".$quantity."', '".$_SESSION['username']."')")or die(mysql_error());
echo $_SESSION['username'];
}
}
echo implode(',', $message);
echo "<br/>";
echo "<br />Record inserted";
echo "<br/>";
echo $date;
}
else { echo "You did not choose a quantity."; }
}else { echo "You did not choose any product."; }
}
?>
Why is username undefined?
A part of members.php:
<?php
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ((!$username) || (!$password)) {
do_html_header('');
echo '<h3 style="color:#800000;">Please fill in both fields</h3><br><br></br></br>';
display_login_form();
}
else {
$sql = mysql_query('SELECT * FROM members WHERE username="'.$_POST['username'].'" AND password=sha1("'.$_POST['password'].'")') or die(mysql_error());
$login_check_member = mysql_num_rows($sql);
if($login_check_member > 0) {
while($row = mysql_fetch_array($sql)) {
$role = $row["role"];
$_SESSION['role'] = $role;
$us = $row["username"];
$_SESSION['username'] = $us;
$username = $_SESSION['username'];
}
}
I include this file in my addorder.php file.
Probably because it's not defined?
Seems people are a little more concerned about your SQL than anything -- but this may help you in the actual question.
Throw this in there before them nested conditions:
if (defined($_SESSION['username'])) {
echo 'Username is defined!';
}
else {
die('Username is undefined!');
}

Categories