Nothing show ups in MySQL database - php

I have a problem displaying my information in the database using phpmyadmin. I have 2 files (form.php and connect.php), it says it's connected to the database but nothing shows up in my database.
Is there any solution for that? I spent almost a whole day trying to resolve that.
Here's connect.php:
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password=''; **i don't have a password.
mysql_connect($mysql_host,$mysql_user,$mysql_password)
echo"connection sucess";
$link = mysqli_connect("localhost","root","") or die ("Couldn't not connect");
mysqli_select_db($link, "cooperative_db");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo "Successfully connected \n";
$FIRST_NAME = $_POST['FIRST_NAME'];
$LAST_TIME = $_POST['LAST_NAME'];
$CIVIC_NUMBER = $_POST['CIVIC_NUMBER'];
$STREET = $_POST['STREET'];
$CITY = $_POST['CITY'];
$PROVINCE = $_POST['PROVINCE'];
$POSTAL_CODE = $_POST['POSTAL_CODE'];
$COUNTRY = $_POST['COUNTRY'];
//$TELEPHONE = $_POST['TELEPHONE'] . $_POST['TELEPHONE'] . $_POST['TELEPHONE'];
$INCOME = $_POST['INCOME'];
//$INCOME_SOURCE = $_POST['element_6_1'] . $_POST['element_6_2'] . $_POST['element_6_3'] . $_POST['element_6_4'] .
//$_POST['element_6_5'];
$sql = "INSERT INTO candidat(FIRST_NAME, LAST_NAME, CIVIC_NUMBER, STREET, CITY, PROVINCE, POSTAL_CODE, COUNTRY, INCOME) VALUES ('$FIRST_NAME', '$LAST_TIME', '$CIVIC_NUMBER', '$STREET','$CITY', '$PROVINCE', '$POSTAL_CODE', '$COUNTRY', '$INCOME')";
?>

It seems like you may have many issues in your code. Let's start step by step.
I am not sure if that: "**i don't have a password." is actually inside your code, so change it first of all to //i don't have a password..
Now, in the second picture you showed us, it only echo 1 line instead of two, and inside your code you actually have two lines that should echo a result.
echo"connection sucess"; and echo "Successfully connected \n";
This could be due to the fact that you forgot a ; in the line right before the first echo.
mysql_connect($mysql_host,$mysql_user,$mysql_password);
May I ask you why are you using both mysql, and mysqli? If it's just for testing, there's no harm in it, plus you should know that mysql is deprecated and no longer supported or updated, you better just use mysqli, please refer to this post Why shouldn't I use mysql_* functions in PHP?.
The first picture shows that you don't have a table named candidat, yet in your code you have this: INSERT INTO candidat. Maybe you wanted this to be INSERT INTO cooperative_table instead?
Please make those small fixes, and tell us your result.
Edit: I forgot to mention, just like tadman commented, you better be aware of the SQL Injection bugs you have and fix them accordingly.

Related

Tutorial issues using INSERT INTO without adding a row to database for certain entries

I am following the last part of the following video tutorial "How to create a database website with PHP and mySQL 07 - Add in input form" :
https://www.youtube.com/watch?v=MGIG00d1Xzc&list=PLhPyEFL5u-i0zEaDF0IPLYvm8zOKnz70r&index=7
At the end here is my code, for the inserting portion to the database for the new_jokes.php script (everything up to this point of the series I have gotten to work fine so far)
Basically I am getting the seemingly classic "INSERT INTO" not working although all my syntax looks correct. Am I missing something obvious here? I get no errors, just the row isn't added.
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question
$new_joke_answer </h2>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES
(NULL, '$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
include "search_all_jokes.php";
?>
Return to the main page
Here is the db_connect.php code as requested:
<?php
// four variables to connect the database
$host = "localhost";
$username = "root";
$user_pass = "usbw";
$database = "test";
// create a database connection instance
$mysqli = new mysqli($host, $username, $user_pass, $database);
?>
Here is search_all_jokes.php (which has minor error checking):
// if there are any values in the table, select them one at a time
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "SELECT JokeID, Joke_question, Joke_answer FROM Jokes_table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "JokeID: " . $row["JokeID"]. " - Joke_question: " .
$row["Joke_question"]. " " . $row["Joke_answer"]. "<br>";
}
} else {
echo "0 results";
}
?>
Also here is the table structure screenshot viewed in myPHPAdmin:
I added error capturing into new_jokes.php inspired by this Stack Overflow post:
INSERT INTO SYNTAX ERROR
And get the following error:
Error: 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 't jump.' )' at line 1localhost via TCP/IP
Thank you everyone for helping out with this! Syntax can really throw a wrench in everything. I also will read up on prepared statements since that also could have prevented the issue. The ultimate help to this I found the solution to by adding the function referenced here for MySQLi real_escape_string to clean the single quote I had within the answer I was submitting to my joke table:
(Can a kangaroo jump higher than the empire state building? Of course, the empire state building can't jump.)
As shown in the documentation #miken32 linked as a comment here it is says: "But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)"
But now the code for this part 7 of the tutorial on you tube I found works and adds it into a row on the database table, then displaying the full new table on the next webpage. I spent a good while shooting in the dark on while the answer ended up being fairly simple. Again special thanks to #miken32 for pointing me the right direction.
Here is my completed code that ended up working to at least achieve the goal of the tutorial:
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
$new_joke_question = $mysqli->real_escape_string($new_joke_question);
$new_joke_answer = $mysqli->real_escape_string($new_joke_answer);
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question $new_joke_answer
</h2>";
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES (' ',
'$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
if ($mysqli->query($sql) === TRUE) {
echo 'users entry saved successfully';
}
else {
echo 'Error: '. $mysqli->error .'<br>';
}
include "search_all_jokes.php";
?>
Return to the main page

sql connecting two forms to a database

I'm a beginner when it comes to the topic. I've followed this tutorial to connect one form to a database and it worked well. Now I'd like to add another form and my questions are:
do I create separate function in connection.php?
do I create a separate table in the same database?
how do I generate a separate thank you message?
The other form is a contact form.
connection.php:
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "responses";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
thankyou.php
<?php
require 'connection.php';
$conn = Connect();
$email = $conn->real_escape_string($_POST['u_email']);
$query = "INSERT into newsletter (email) VALUES('" . $email . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
echo $_GET["form"];
echo "Thank you for subscribing to our newsletter. <br>";
$conn->close();
?>
The second form would look like this:
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$message = $conn->real_escape_string($_POST['message']);
$query = "INSERT into contactForm (name,email,message) VALUES('" . $name . "','" . $email . "','" . $message . "')";
$success = $conn->query($query);
I've created two tables: newsletter and contactForm. Now, how do I direct form input to the right table?
1 - You can "require"/"include" the same connection.php wherever it suit you / need it
2 - you can create on the same Database a new table and do action on this new on your query example:
$query = "INSERT into newsletter (email) VALUES('" . $email . "')";
$success = $conn->query($query);
$query = "INSERT into newsletter_schedule (email,schedule_date) VALUES('" . $email . "', NOW())";
$success = $conn->query($query);
or you can create in a different db and change db name connected(more complex but sometimes needed)
3 - you can do in separate static file and redirect to using (PHP function)
header("location: tankyou.html");//put your file name/must be the first output, even a space before can throw a error
leave more details about the 3rd if is not what you are looking for
Unfortunately, your question, "How do I...?" is a bit broad in this case. Any number of ways. The only real way to get a sense for these things is to try a number of times. You may fail, but that's where the most learning happenings.
Your specific questions:
do I create separate function in connection.php?
Depends on what you need. I might include a 'CloseConnection' or 'TearDown' function, but doing so is not strictly necessary in PHP. (PHP does it's best to close down and stop using any resources you still have open at the end of your script.)
However, if you want to edge toward better practices, get in the habit now of always cleaning up after yourself. What you learned in kindergarten applies: if you opened it, close it. If you created it, dispose of it. If you allocated it, deallocate it. etc.
do I create a separate table in the same database?
Yes. This question is related to schema design, and again, you will just have to try things out and see what works for your situation and thought processes. You will know that things are not right when the logic gets really convoluted. But knowing that comes with nothing other than experience.
how do I generate a separate thank you message?
The same way you generate any other HTML. Some version of echo, print, or include/require. Given your current setup, I might create a separate function for this logic.
One thing which is not what you asked for, but which I feel compelled to point out: heavily consider prepared statements for your SQL, rather than string interpolation. That is ...
BAD:
$query = "INSERT into newsletter (email) VALUES('" . $email . "')";
$success = $conn->query($query);
BETTER/GOOD:
$sql = "INSERT INTO newsletter (email) VALUE ( ? )";
$statement = $conn->prepare( $sql );
$statement->bind_param('s', $email);
$statement->execute();
This is perhaps slightly more complicated, but also precludes any need for sanitization like real_escape_string.
For more information, read the documentation and google prepared statements, but the gist is this: for security reasons now, and higher performance later. By telling the database what will be coming, you preclude someone from injecting something you didn't expect or want.

PHP not running when trying to connect to MySQL database

I'm trying to create a simple web page that will allow students to sign out for the day using just their school username.
I have written some code to take the users input from the HTML form called "Username" and connect to a database containing all the students usernames.
It will then find the student's details within the database and sign them out.
So far all the client side code works, but as soon as the PHP try's to connect to the database, everything stops running and no error codes appear apart from the occasional HTTP 500 Error depending on which part of the code I isolate?
<html>
<head>
<?php include 'head.php'; ?>
</head>
<body>
<form method="post" action="/index.php" class="login_form">
<input type="text" name="Username" placeholder="School Username">
<input type="submit" value="Sign Out">
</form>
<?php
session_start();
// These details are used for logging in
$sql_servername = "localhost";
$sql_username = "root";
$sql_password = "NotaRealPassword";
$sql_database = "student_info";
$username = $_POST['Username'];
echo "Test 1";
// Create connection
$con = mysqli_connect($sql_servername, $sql_username, $sql_password, $sql_database);
echo "Test 2";
// Check Connection
if (!$con){
die("Connection Failed: " . mysql_error());
}
echo "Connected To Database Sucessfully! ";
echo "Test 3";
//Perform Queries
$result = mysql_query(con, "SELECT user_name, first_name, last_name FROM student_id WHERE user_name='" . $username . "';");
echo "Test 4";
echo "Username: " . $username . "<br>";
echo "Username: " . $UN . "<br>";
echo "First Name: " . $FN . "<br>";
echo "Last Name: " . $LN . "<br>";
echo "Database Output: " . $result;
//Close Connection
mysqli_close($con);
?>
You are mixing mysqli_* and mysql_*, don't think that makes sense. Also as mentioned in the comments, this is unsafe - it puts you at risk of SQL injection. Take a look at PDO.
The query you want to execute, needs the $con variable, yet you forgot to write the $. Which means you'd get an error.
$result = mysql_query(con, "SELECT user_name, first_name, last_name FROM student_id WHERE user_name='" . $username . "';");
Should be, but also should not be:
$result = mysqli_query($con, "SELECT user_name, first_name, last_name FROM student_id WHERE user_name='" . $username . "';");
1) Your session_start() is in the wrong place.
2) You're mixing mysql_ with mysqli_ PHP functions. They are not compatible.
3) As referenced in comments you are referencing a variable but you've forgotten to add the $ , so it's actually be assumed to be a CONSTANT (which is undefined).
4) You would have found all of these things out yourself if you've used PHP Error reporting.
5) Your MySql result ($result = mysql_query(...)) is not usable, it's an SQL result and not something PHP can naturally handle.
As a worse case fix you want to be using $output = mysqli_fetch_array($result); or similar methods to turn the result into usable PHP variables. Even better if you read point 6 and employ Prepared Statements.
6) Your SQL code is unsafe and you should urgently look at using PHP Prepared Statements.
Please read suggestion 4 again, and now you've read it twice, read it a third time and checkout the link. This suggestion will save you hours of time, and will help you learn your craft, rather than asking Stack Overflow for answers.
Cheers.

PHP Sql injection vulnerable [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I wrote the below script as my very first ever php mysql application. I am self taught and the code works as intended. My host thinks it may be vulnerable to sql injection attacks but cannot tell me why or what I should change to make it better. I'm sure it's not as clean as it could be but if anyone has any suggestions or insight I would certainly appreciate it.
<form method="post" action="search.php?go" id="searchform">
<?php
$db=mysql_connect ("server", "*", "*") or die ('I cannot connect to the database because: ' . mysql_error());
$mydb=mysql_select_db("*");
$category_sql="SELECT distinct category FROM Members";
$category_Options="";
$category_result=mysql_query($category_sql) or die ('Error: '.mysql_error ());
while ($row=mysql_fetch_array($category_result)) {
$category=$row["category"];
$category_Options.="<OPTION VALUE=\"$category\">".$category.'</option>';
}
?>
<p>
<SELECT NAME="category"><OPTION VALUE=0>Choose<?=$category_Options?></SELECT>
</p>
<input name="submit" "id="submit" type="submit" value="submit" />
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
$category=$_POST['category'];
$category=mysql_real_escape_string($category);
$sql="SELECT category, company, address, city, state, zip, phone, web, addescription, image
FROM Members
WHERE category LIKE '$category'";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
$category2=$row["category"];
$company=$row["company"];
$address=$row["address"];
$city=$row["city"];
$state=$row["state"];
$zip=$row["zip"];
$phone=$row["phone"];
$web = $row["web"];
$addescription = $row["addescription"];
$image = $row["image"];
echo "<blockquote>";
if(#file_get_contents($image))
{
echo "<img src='".$image ."' class='image'/>\n";
}
else
{
}
echo "<p>\n";
echo "</br>".$category2 . "\n";
echo "</br><b>".$company . "</b>\n";
echo "</br>".$address . "\n";
echo "</br>".$city . ", ".$state. " ".$zip . "\n";
echo "</br>".$phone . "\n";
echo "</br>".$web ."\n";
echo "</br>".$addescription . "\n";
echo "</br><a href=http://www.printfriendly.com style=color:#6D9F00;text-decoration:none; class=printfriendly onclick=window.print();return false; title=Printer Friendly and PDF><img style=border:none; src=http://cdn.printfriendly.com/pf-button.gif alt=Print Friendly and PDF/></a>\n";
echo "</p>";
echo "</blockquote>"
;
}
}
else{
echo "<p>Please select a Category</p>";
}
}
mysql_close($db)
?>
The MySQL functions are deprecated. Using the MySQLi functions, and prepared statements, are a better way to protect against sql injection attacks.
$stmt = $mysqli->prepare('SELECT category, company, address, city, state, zip, phone, web, addescription, image FROM Members WHERE category LIKE ?');
$stmt->bind_param('s', $category);
I'll show the implementation of a PDO connection and how to query with it. Here it goes!
First we create the connection variable with your database credentials. We'll store this connection in $db.
$username = "root";
$password = "";
$host = "localhost";
$dbname = "my_database";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8"; $username, $password, $options);
}catch(PDOException $ex){
die("Failed to connect: ".$ex->getMessage());
}
Now you have a PDO connection stored in $db which you can query through. You may want to account for magic quotes if you're not using PHP 5.4, so keep that in mind.
Otherwise, create your query statement like so..
$query = "SELECT category, company, address, city, state, zip, phone, web, addescription, image FROM Members WHERE category LIKE :category"
Afterwards, you want to bind the value from the $_POST['category'] variable (or $category since you created that) to the parameter :category. Do that like so:
$query_params = array( ':category' => $category);
Finally, now that you have the statement and the parameters, use the previously created $db variable to prepare and execute the statement.
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
Since we're SELECTing data where it could return multiple rows (assuming you have multiple rows within a category), we need to account for that. Grab the rows that the statement returns like so:
$rows = $statement->fetchAll();
And now you could refer to column headers within each $row of the database table by utilizing a foreach statement.
$citiesArray = array();
foreach($rows as $row){
if(isset($row['city'])){
$citiesArray[] = $row['city'];
}
}
Hope that helps out!
Just remember the golden rule of never trusting your users. Never take any raw user input and insert it into a database, as there's a chance that you have left yourself wide open for a security issue.
Your code seems fine. However, do note that MySQL is deprecated as of PHP 5.5.0, and instead you should use MySQLi or PDO extension which provide more security.
Maybe that's the reason your host said such thing, but from a quick look on your code it seemed fine to me.
Cheers.
The problem is the follwoing part in your code
$sql = "SELECT category, company, address, city, state, zip,
phone, web, addescription, image
FROM Members
WHERE category LIKE '$category'";
$result=mysql_query($sql);
If the parameter $category is read from the GET or POST parameters, it should be escaped:
$sql = "SELECT category, company, address, city, state, zip,
phone, web, addescription, image
FROM Members
WHERE category LIKE '" . mysql_real_escape_string($category) . "';";
If you are doing it this way, the variable cannot be used for SQL Injection
By the way (like Matthew Johnson said), the procedural mysql extension is deprecated since PHP 5.5. You should better use Mysqli or PDO.
The OOP way (strongly recommended) would look like:
$pdo = new PDO($dsn, $user, $password, $options);
$statement = $pdo->prepareStatement(
"SELECT category, company, address,
city, state, zip, phone, web,
addescription, image
FROM Members
WHERE category LIKE :category;");
$statement->bindParam(':category', $category, PDO::PARAM_STR);
$statement->execute();
$categories = $statement->fetchAll();

What is wrong with my MySQL query?

So, I have a form that posts to my php file using ajax, and succeeds. But the following query doesn't insert anything. Can someone help me understand what I'm doing wrong?
My php file:
<?php
include 'connect.php' ;
$type = mysql_real_escape_string($_POST['type']);
$title = mysql_real_escape_string($_POST['title']);
$content = mysql_real_escape_string($_POST['content']);
if ($type == 'Just Text') {
mysql_query("INSERT INTO articles (title, type, thisisaninteger, content) VALUES ('".$title."', '".$type."', 0, '".$content."')")or die("MySQL Error: " . mysql_error());
}
?>
My connect.php:
<?php
$dbhost = "localhost";
$dbname = "example";
$dbuser = "test";
$dbpass = "test";
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
?>
If you aren't receiving any errors and the INSERT just doesn't happen, it is most likely because the if statement fails to be true. Verify that $type actually matches Just Text.
You should also be inserting values using prepared statements, and use PDO or MySQLi - this article will help you decide which.
first, echo "something" after the if statement and recall the data with your ajax post. you can find out if your if statement is working, then try formatting your variables like so
mysql_query("INSERT INTO articles (title, type, thisisaninteger, content) VALUES ('$title', '$type', 0, '$content')")or die("MySQL Error: " . mysql_error());
I just want to throw in an official vote/recommendation in favor of switching to a parameterized SQL statement, too. In spite of the use of mysql_real_escape_string, schlepping a SQL statement together via string concatenation is neither necessary nor a good idea. Honestly, I find a prepared statement much, much easier to read than the typical string-concatenation exercise, as well:
$stmt = $dbh->prepare("SELECT * FROM users WHERE USERNAME = ? AND PASSWORD = ?");
$stmt->execute(array($username, $password));
Alright, it was a stupid mistake on my side. There were columns I didn't include and they were not being assigned a value. Thanks everyone for helping out.

Categories