mySQL insert wont update database - php

I have a form that sends data to the php below. No errors appear but no information is inserted into the database and I don't understand why. I have triple checked all the table names etc and everything is correct. The code echo's out what I put into the form but it doesn't update to the database!
<?php
//variables for db
$username = "";
$password = "";
$hostname = "localhost";
$dbname = "infinity";
//connection to the database
$con = mysql_connect($hostname, $username, $password);
if($con == FALSE)
{
echo 'Cannot connect to database' . mysql_error();
}
mysql_select_db($dbname, $con);
$name=$_POST["name"];
$logo=$_POST["logo"];
$logo="<img src=\"images/".$logo."\" alt=\"$name Logo\" />";
$blurb=$_POST["blurb"];
$link=$_POST["link"];
echo $name;
echo $logo;
echo $blurb;
echo $link;
//Insert Values into Database
mysql_query("INSERT INTO `infinity`.`sponsors` (`name`, `logo`, `blurb`, `link`) VALUES ('$name', '$logo', '$blurb', '$link');");
?>

Try to get an error message of you query:
mysql_query($your_query) OR die(mysql_error());

try this
mysql_query("INSERT INTO `infinity`.`sponsors` (`name`, `logo`, `blurb`, `link`)
VALUES ('$name', '$logo', '$blurb', '$link')") or die(mysql_error());
else you make check it.
$sql ="INSERT INTO `infinity`.`sponsors` (`name`, `logo`, `blurb`, `link`)
VALUES ('$name', '$logo', '$blurb', '$link')";
$sqlinset= mysql_query($sql) or die(mysql_error());
echo $sql;
echo $sqlinset;

Try this:
mysql_query("INSERT INTO `infinity`.`sponsors` (`name`, `logo`, `blurb`, `link`) VALUES ('$name', '$logo', '$blurb', '$link');", $con);
And be sure to secure those variables you put in your database from SQL ijection and XSS attacks.

Related

How to insert data into MySQL using MySQLi?

I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname = $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";
mysqli_close($con);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());
echo 'connected';
// Select the database.
// mysqli_select_db($con, "kraus");
$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";
// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);
// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
echo "1 record added";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.

Unknow column in field list. Couldn't find what went wrong

This is the error that I got Error:Unknown column 'David Beckham' in 'field list'
I am stucked here for about 2 hours trying to figure what went wrong.
Anyone here mind to point out what's wrong with my code ?
Your help is greatly appreciated.
<?php
define('DB_NAME', 'testdb');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
//logon
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link){
die('Could not connect: '. msql_error());
}
// select the database you gonna work with
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Cant use' . DB_NAME . ':' . mysql_error());
}
$value = $_POST['FullName'];
$value2 = $_POST['Email'];
$value3 = $_POST['Postcode'];
$value4 = $_POST['DateofBirth'];
$value5 = $_POST['Gender'];
//insert into table.
$sql = "INSERT INTO vajayjay (FullName, Email, Postcode, DateofBirth, Gender) VALUES (`$value`, `$value2`, `$value3`, `$value4`, `$value5`)";
if(mysql_query($sql)){
echo "Thank you for signing up";
}else{
die('Error:'. mysql_error());
}
mysql_close();
?>
You are using backtrics for varibles.it is only for columns
$sql = "INSERT INTO vajayjay (`FullName`, `Email`, `Postcode`, `DateofBirth`, `Gender`) VALUES ('$value', '$value2', '$value3', '$value4', '$value5')";
USE backtrics for Column names
(`FullName`, `Email`, `Postcode`, `DateofBirth`, `Gender`)
USE Quotes for variables for escaping purpose
('$value', '$value2', '$value3', '$value4', '$value5')
Remove the backticks from the variables
The right way..
$sql = "INSERT INTO vajayjay (`FullName`, `Email`, `Postcode`, `DateofBirth`, `Gender`) VALUES ('$value', '$value2', '$value3', '$value4', '$value5')";
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !

MySQL Query Not Working - No Errors

For some reason my query isn't working, I'll post the code and output of $_POST.
I will also add a screenshot for the structure of the database.
$_POST:
Code:
ini_set('display_errors',1);
error_reporting(E_ALL);
echo "<pre>";
var_dump($_POST);
echo "</pre>";
$mysqli = new mysqli("localhost", "lunar_casino", "******", "lunar_casino");
if(isset($_POST['submit'])){
$error = array();
if(empty($error)){
$bonus = $_POST['bonus'];
$deposit = $_POST['deposit'];
$offers = $_POST['offers'];
$link = $_POST['link'];
$name = $_POST['logo'];
$q = $mysqli->query("INSERT INTO `lunar_casino`.`casino` VALUES(NULL, '$bonus', '$deposit', '$offers', '$link', '$logo', '$name', NULL)");
if(!$q){
echo "<font color='red'><b>There has been an error with our database! Please contact the website administrator!</b></font><br /><br />";
} else {
echo "<font color='green'><b>You have successfully added the casino!</b></font><br /><br />";
}
} else {
echo "<font color='red'><b>There were ".count($error)." errors in your form:</b></font><br />";
foreach($error as $err){
echo "<b>".$err."</b><br />";
}
echo "<br />";
}
}
Structure of Database:
If you need more information just let me know!
By the way, the way I know the error is in the query is because I checked if(!$q) and made it display an error message if the query can't be done, and it displays the error message on the page.
Any ideas why its not working? Also I left out date from the query because I don't know how to add the current date:time into the query.
If anyone could help with either of these issues please let me know! :)
I think the problem is that you set NULL the date column. Try NOW() instead of NULL:
$q = $mysqli->query("INSERT INTO `lunar_casino`.`casino` VALUES(NULL, '$bonus', '$deposit', '$offers', '$link', '$logo', '$name', NOW())");
Your error here is isn't very clear. Here are some debugging options you can try:
Name the fields
$q = $mysqli->query("INSERT INTO `lunar_casino`.`casino` VALUES(NULL, '$bonus', '$deposit', '$offers', '$link', '$logo', '$name', NULL)");
to
$q = $mysqli->query("INSERT INTO `lunar_casino`.`casino`(field1, field2...) VALUES(NULL, '$bonus', '$deposit', '$offers', '$link', '$logo', '$name', NULL)");
Save your query to a string and print it out. (Gordon Linoff)
echo "INSERT INTO `lunar_casino`.`casino` VALUES(NULL, '$bonus', '$deposit', '$offers', '$link', '$logo', '$name', NULL)"
before the query. This can show you what PHP is making for MySQL to feed on.
Check for errors
if ($mysqli->connect_errno) { //check connection error
printf("Connect failed: %s\n", $mysqli->connect_error); //check query error
exit();
}

php insert to sql not working

I'm on ubuntu running on apache2.
<?php
$con = mysqli_connect("localhost", "root", "password", "loops");
if (!mysqli_connect_errno()) {
echo "Error to connect: ".mysqli_connect_error();
}
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$age = $_POST['age'];
echo "First: ".$firstName."<br />Age: ".$age;
$sql = "INSERT INTO persons (FirstName, LastName, Age)
values (".$firstName.",".$lastName.",".$age.")";
if (!mysqli_query($con)) {
die("Error :".mysqli_error($con);
}
echo "1 added";
mysqli_close($con);
?>
I don't know what to do now, but the error seems to be on the '$sql', 'cause when I put that
under a comment, the rest works...
You forgot the infamous mistake of wrapping the varchar variables with single quote '
"INSERT INTO persons (FirstName, LastName, Age)
values ('".$firstName."','".$lastName."','".$age."')";
Additionally, It's highly risky for you, not be using protections against SQL Injections
Try this, mysqli_query($con, $sql) You need to execute the query so that it will store into the database
$sql = "INSERT INTO persons (FirstName, LastName, Age)
values ('".$firstName."','".$lastName."','".$age."')";
if (!mysqli_query($con, $sql)) {
...................^
die("Error :".mysqli_error($con);
}
Try this:
$sql = "INSERT INTO persons (`FirstName`, `LastName`, `Age`) values (".$firstName.",".$lastName.",".$age.")";
If this doesn't work, what error do you get.

php inserting to database fail

I have following message box error, says Failed. these are my codes:
<?php
require('admin/connectdb.php');
if (isset($_POST['Sub']))
{
//get data from reservation form
$cutomername=$_POST['aname'];
$gender=$_POST['sex'];
$phoneno=$_POST['tel'];
$email=$_POST['email'];
$age=$_POST['age'];
$computerpart=$_POST['partcomp'];
$option1=$_POST['option1'];
$notes=$_POST['Notes'];
$query="INSERT INTO `assignmentwebprog`.`reservation` (`cumstomername`, `gender`, `phoneno`, `email`, `age`, `typeofcomputerpart`, `option`, `notes`)
VALUES ('$cutomername', '$gender', '$phoneno', '$email', '$age', '$computerpart', '$option1', '$notes')";
$qresult = mysql_query($query);
if ($qresult){
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
}
else
{
echo "<script type='text/javascript'>alert('failed!')</script>";
}
}
?>
up there is inserting value to phpmyadmin & every time i load/input then click enter then the page shows message box "failed"
these are my database:
<?php
$host="localhost"; // Host name
$username="root"; // username
$username="root"; // username
$db_name="assignmentwebprog"; //database name
$tbl_name="reservation";
// Replace database connect functions depending on database you are using.
mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");
?>
currently my database is phpmyadmin, is there something missing with my code?
Check to see if the field in the database cumstomername is spelt correctly.
It should probably be customername
Passing the paramter
$cutomername=$_POST['aname'];
SQL
$query="INSERT INTO `assignmentwebprog`.`reservation` (`cumstomername`, `gender`, `phoneno`, `email`, `age`, `typeofcomputerpart`, `option`, `notes`)
VALUES ('$cutomername', '$gender', '$phoneno', '$email', '$age', '$computerpart', '$option1', '$notes')";
Change this line and try:
$qresult = mysql_query($query) or die(mysql_error());
check this :
$query="INSERT INTO reservation (cumstomername, gender, phoneno, email, age, typeofcomputerpart, option, notes)
VALUES ('$cutomername', '$gender', '$phoneno', '$email', '$age', '$computerpart', '$option1', '$notes')";
$qresult = mysql_query($query) or die(mysql_error());
You might have missing something in the $query which is mandatory for the table insertion.
First echo the query on the page. // echo $query ;
Then RUN the query in phpmyadmin and you will get the reason why it is not inserting in the table. See the error there.

Categories