mysql - can't insert data into database with php - php

I'm tryin to add users to my MYSQL database with PHP, somehow it is not working. Check my script below. What am i doing wrong?
<html>
<head>
</head>
<body>
<form action="index2.php" method="post">
Voornaam: <input type="text" name="voornaam"><br />
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit'])) {
$con = mysql_connect("localhost","hakan","hakan");
if (!$con) {
die ("Can not connect: " . mysql_error());
}
mysql_select_db("projectfys",$con);
$sql = "INSERT INTO gebruikers (voornaam) VALUES ('voornaam')";
mysql_query($sql,$con);
mysql_close($con);
}
?>
</body>
</html>

$con needs to be in first place
E.g.
mysql_select_db($con,'db');
mysql_query($con,$sql);
Change the direction everywhere.
Also, change everything to mysqli, you can find masses of tutorials for mysqli or PDO
This block should look like (with mysqli):
$con = new mysqli("localhost","hakan","hakan","projectfys");
$con -> set_charset ( 'utf8' );
if ($con->connect_errno) {
printf("Connect failed: %s\n", $con->connect_error);
exit();}
mysqli_query($con, "INSERT INTO gebruikers (voornaam) VALUES ('voornaam')");
$con -> close();
EDIT
With your query, you will allways insert the string "voornaam" in your table.
You need to do this before:
$voornaam = $_POST['voornaam'];
$voornaam = mysqli_real_escape_string($con,$voornaam);
Add this after your connection and before the query. In the query, replace the second 'voornaam' with '$voornaam'
mysqli_query($con, "INSERT INTO gebruikers (voornaam) VALUES ('$voornaam')");

Related

Can I run a sql query in another file?

I am busy with a school project to learn MVC. But I know very little of php.
I have an dbconnection file and it looks like this
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "filmopdrachtdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connet_error);
}
echo "Connected SuccessFully";
I have a login page that looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="../Controllers/UserController.php" method="post">
Gebruikersnaam <input type="text" name="naam">
Wachtwoord <input type="password" name="wachtwoord">
<input type="submit" value="Login">
</form>
</body>
</html>
And I have an User Controller that looks like this:
<?php
include_once ("../Includes/DbConnection.php");
include_once ("../Models/User.php");
$gebruiker = new User();
$naam = $gebruiker->setGebruikersnaam($_POST["naam"]);
$wachtwoord = $gebruiker->setWachtwoord($_POST["wachtwoord"]);
$stmt = "SELECT gebruikersnaam, wachtwoord FROM klanten";
var_dump($stmt);
How do I run the $stmt query. I don't understand what I have to do
$stmt = "SELECT gebruikersnaam, wachtwoord FROM klanten";
EDIT: I want the query $stmt to run in the UserController. Not in the DbConnection file.
If you use stm, you can execute with that code:
$stmt=$conn->prepare("SELECT gebruikersnaam, wachtwoord FROM klanten WHERE user=?");
$stmt->bind_param('s',$naam);
$stmt->execute();
OR
$conn->query($stmt);
In your DbConnection.php file you have a $conn variable which contains your connection to the database. From that variable you can execute your queries on the database.
From the mysqli PHP documentation, modified to work with your code:
$results = $conn->query($stmt);
Please note that this method should not be used with a dynamically generated query string:
//BAD practice, leads to SQL injection
$results = $conn->query("SELECT * FROM MyTable WHERE myColumn = $search LIMIT 10");
For dynamically generated queries use prepared queries.
I could also suggest to use PDO which is a more versatile database interaction libraray in PHP, which you will probably not be able to do for that code as it is for school, but for your own projects :)

Data not showing up on Wamp server database (using php)

I'm trying to INSERT data into a table in my database but I'm not able to. I'm using WAMP.
PHP Script:
$user = 'root';
$password = '';
$db = 'comments_schema';
$host = 'localhost:3306';
$mysqli = mysqli_connect('localhost', $user, $password, $db);
$sql = "INSERT INTO parent_comment(commentid, comment) VALUES ('". '
commentid'."', '". "hi" ."')";
$result = $mysqli->query($sql);
if($result > 0):
echo 'Successfully posted';
else:
echo 'Unable to post';
endif;
HTML Code:
</div>
<form action="database.php" method="post">
Comments: <input type="text" name="field_name" />
<input type="Submit" /></form>
However, the rows could not be inserted:
You can use backticks for SQL-related elements, ands single quotes around the values you want to insert.
$sql = "
INSERT INTO `parent_comment` (commentid, comment)
VALUES ('commentid', 'hi')
";
You can try this code:
'INSERT INTO parent_comment(commentid, comment) VALUES ('.commentid.', "hi")';

Non object error when using prepared statement

I have a table containing columns person and person_initials. When Submit is clicked I would like to insert the name in the input box into the person column in the table of names where the initial equals the initial defined. In this case only 1 row containing "I" in the person_initial column exists in the table.
Please see the code below. I'm sure there must be a basic syntax error in the prepared statement but I can't see it. Apologies for the ignorance.
index.php:
<html>
<body>
<form method="post">
Insert: <input type="text" name="q" value="Tim"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$test_name = $_POST['q'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "personnames";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$people = 'I';
$stmt = $conn->prepare("INSERT INTO names (person) VALUE=(?) where
person_initial=(?)");
$stmt->bind_param("ss",$test_name,$people);
$stmt->execute();
$stmt->close();
$conn->close();
}
?>
</body>
</html>
You seem to attempting an update, in which case the syntax would be:
$stmt = $conn->prepare("UPDATE names SET person=? where person_initial=?");
Your INSERT query is wrong. Use
$stmt = $conn->prepare("INSERT INTO names (person) VALUES(?)");
instead
$stmt = $conn->prepare("INSERT INTO names (person) VALUE=(?) where
person_initial=(?)");
If you want to update, then use update query like this
$stmt = $conn->prepare("UPDATE names SET person=? where person_initial=?");

Post will not insert into MySQL Database

I've been searching around for like 15 minutes and could not find anything that would fix this. Sorry if I just used wrong keywords or something it has been answered. Also to state this is not something that needs to be extremely secure, as anybody can view this.
So my PHP Post will not insert into MySQL Database.
Form:
<form method="post" action="./thankyou.php">
<h2>Please sign in</h2>
<input type="user"name="user" placeholder="Username">
<input type="textarea" class="" name="feedback" placeholder="Feedback for us."><br />
<button class="" type="submit" name="submitted">Submit Feedback</button>
</form>
Thank you: (Yes I replaced xxx with info)
<?php
$conn = mysql_connect('xxx', 'xxxx', 'xxxx');
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxx") or die(mysql_error());
$user = $_POST['user'];
$fdb = $_POST['feedback'];
$insert = "INSERT INTO contact WHERE (user, feedback) VALUES ('".$user."', '".$fdb."')";
mysql_query($insert);
if(!$insert)
{
die('Could not enter data: ' . mysql_error());
}
echo $insert;
?>
Echo outputs correctly:
INSERT INTO contact WHERE (user, feedback) VALUES ('thisisauser', 'thisisfeedback')
I'm not sure what to do.
An insert does not, by definition, have a where clause.
Change your query as follows:
INSERT INTO contact (user, feedback) VALUES ('thisisauser', 'thisisfeedback')
OR, you can use this structure:
INSERT INTO contact SET user = 'thisisauser' , feedback = 'thisisfeedback'
Finally, this is bad for security. Use a different database API
You dont need to provide WHERE in insert its not correct
it should be
$insert = "INSERT INTO contact (user, feedback) VALUES ('".$user."', '".$fdb."')";
You had as
$insert = "INSERT INTO contact WHERE (user, feedback) VALUES ('".$user."', '".$fdb."')";
^.........here is the issue
The main issues are the SQL query and the way of you check the correct execution of the query
<?php
$conn = mysql_connect('xxx', 'xxxx', 'xxxx');
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxx") or die(mysql_error());
$user = $_POST['user'];
$fdb = $_POST['feedback'];
$insert = "INSERT INTO contact (user, feedback) VALUES ('".$user."', '".$fdb."')";
$retval = mysql_query($insert, $conn);
if(!$retval) { //<---- You must check the result of the execution
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";

mysql query not inserting string into table?

I have been able to manually insert values in my table using phpmyadmin, and even if i end up using the same php code i get from php my admin to call the query it STILL won't add the value to the table. here is the code:
<?php
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db('sc2broating1', $link);
$sql = "INSERT INTO `sc2broad_tesing1`.`Persons` (`re`) VALUES (\'hello11\')";
mysql_query($sql);
mysql_close($link);
?>
Don't escape value.
$sql = "INSERT INTO `sc2broad_tesing1`.`Persons` (`re`) VALUES ('hello11')";
I would also consider using bound parameters, as seen in mysqli::prepare, if Mysqli is an option.

Categories