After migrating to PDO from a previous question, I've hit a small snag. I can't insert information into a MySQL table.
Here's what I have:
include_once(db.php);
$platform = $_POST['platform'];
$location = $_POST['location'];
$name = $_POST['name'];
$secret = sha1($_POST['password']);
$sql = $db->prepare("INSERT INTO `servers` (`id`, `secret`, `platform`, `location`, `name`) VALUES (:id, :secret, :platform, :location, :name)");
$sql->bindValue(':id', 'null');
$sql->bindValue(':secret', $secret);
$sql->bindValue(':platform', $platform);
$sql->bindValue(':location', $location);
$sql->bindValue(':name', $name);
$sql->execute();
I can't find a reason why it won't insert new records.
I durr'd hard.
include_once(db.php); needed quotes: include_once("db.php");
I feel like a gigantic moron for wasting 2 hours on why inserting wouldn't work.
Related
My php files that submits an entry to a database table isn't working and I can't figure out why. It takes in an Ajax submit and I know that the problem isn't with the data, or the Ajax request as it processes as a success. The only issue is that no data is ever submitted to my database. I had this working before I changed to code to concatenate the address string where it was one variable before. Any advice would be great!
Here is the php files
UPDATE:::THIS IS THE UPDATED PHP FILE
<?php
require("dbinfo.php");
// Create connection
$conn = new mysqli('localhost', $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_POST['user_name'];
$street = $_POST['user_street'];
$city = $_POST['user_city'];
$state = $_POST['user_state'];
$country = $_POST['user_country'];
$zip = $_POST['user_zip'];
$address = $street.', '.$city.', '.$state.', '.$country.', '.$zip;
$shortAdd = $city.', '.$state.', '.$country;
$type = $_POST['user_color'];
$desc = $_POST['user_message'];
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$address."&sensor=true";
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
if ($status=="OK") {
$lat = $xml->result->geometry->location->lat;
$lon = $xml->result->geometry->location->lng;
}
$sql = "INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`, `desc`)
VALUES (?, ?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssssss', $name, $shortAdd, $lat, $lon, $type, $desc);
$stmt->execute();
$conn->close();
?>
While docliving's answer is correct, please take the extra step and use prepared statements. Your code is vulnerable to SQL injection attacks without it. It just takes a very minor change to convert it to use prepared statements. Here is how to do it with mysqli:
$sql = "INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`, `desc`)
VALUES (?, ?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssssss', $name, $shortAdd, $lat, $lon, $type, $desc);
$stmt->execute();
When #MySelfBoy wrote:
After the assignment, you have to execute SQL statements
He means that you have to execute your query
$sql = "INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`, `desc`)
VALUES ('$name', '$shortAdd', '$lat', '$lon', '$type', '$desc');";
with the following instruction:
$conn->query($sql);
NOTE: I Still canĀ“t make comments, so I'm posting it here.
<?php
require_once 'Connect.php';
//Prepare HTML insert statement binding parameters
$stmt = $conn->prepare("INSERT INTO records (`Title`, `FirstName`, `LastName`, `Gender`, `DOB`, `Mem.Expiry`, `Mem.Type`, `EmailAddress`)
VALUES (:Title, :Fname, :Lname, :Gender, :DOB, :MemX, :MemType, :Email)");
$title = $_POST['Title'];
$fname = $_POST['Fname'];
$lname = $_POST['Lname'];
$gender = $_POST['Gender'];
$dob = $_POST['DOB'];
$memx = $_POST['MemX'];
$memtype = $_POST['MemType'];
$email = $_POST['Email'];
//Attempt row insertion by executing prepared statement
try
{
//Insert a row
$stmt ->bindParam(':Title', $title);
$stmt ->bindParam(':Fname', $fname);
$stmt ->bindParam(':Lname', $lname);
$stmt ->bindParam(':Gender', $gender);
$stmt ->bindParam(':DOB', $dob);
$stmt ->bindParam(':MemX', $memx);
$stmt ->bindParam(':MemType', $memtype);
$stmt ->bindParam(':Email', $email);
$stmt->execute();
}
catch (PDOException $e)
{
echo $e->getMessage();
}
?>
I have a web form that updates a database connected to localhost. I would like to implement a primary key. When I include the ID column and set it to primary key, how can I implement that it auto fills in the code above? I have looked online, but I couldn't find anything helpful.
I cleared the database and inserted a primary key. Now when I fill out the form the first input will be uploaded and the primary key will be 0. After this no other information is being registered?
I think you are looking for Auto Increment
I am trying to make a product spec form add to a table called ProductSpecs on post, however despite the same synatx working fine for SELECT does not work for INSERT. The permissions to the MySQL account used allow full read/write, and I am able to insert into the database via console input using the same request.
Any ideas will be most appreicative.
$sql = " INSERT INTO ProductSpecs (SpecID, Code, ProductName, Barcode, ProductDescription, SKU, CYear, HeaderStyle, Certification, InnerQTY, OuterQTY, PackagingDescription, Comments) VALUES (NULL, '$Code', '$ProductName', '$Barcode', '$ProductDescription', '$SKU', '$CYear', '$HeaderStyle', '$Certification', '$InnerQTY', '$OuterQTY', '$PackagingDescription', '$Comments')";
$result = $conn->query($sql);
Thanks
You don't have to regard SpecID in your query. It should be auto increment not null value, so don't regard it and it will work fine.
You want to try and write your code with prepared statements and you can choose PDO or MySQLI. Here is an example how to do it with PDO. Also I would look at this link it might help you. http://prash.me/php-pdo-and-prepared-statements/ along with these videos https://www.youtube.com/watch?v=bvxid3DoLjE.
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "test123";
$db_name = "test_db";
$dbh = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$stmt= $dbh->prepare("INSERT INTO tests(name1, name2, name3, name4,name5,name6, name7, name8, name9, name10) Values (?,?,?,?,?,?,?,?,?,?)");
$stmt->bindParam(1, $_POST["name1"]);
$stmt->bindParam(2, $_POST["name2"]);
$stmt->bindParam(3, $_POST["name3"]);
$stmt->bindParam(4, $_POST["name4"]);
$stmt->bindParam(5, $_POST["name5"]);
$stmt->bindParam(6, $_POST["name6"]);
$stmt->bindParam(7, $_POST["name7"]);
$stmt->bindParam(8, $_POST["name8"]);
$stmt->bindParam(9, $_POST["name9"]);
$stmt->bindParam(10, $_POST["name10"]);
$stmt->execute();
?>
Try putting columns names inside ``
$sql = "INSERT INTO ProductSpecs (`SpecID`, `Code`, `ProductName`, `Barcode`, `ProductDescription`, `SKU`, `CYear`, `HeaderStyle`, `Certification`, `InnerQTY`, `OuterQTY`, `PackagingDescription`, `Comments`) VALUES (NULL, '$Code', '$ProductName', '$Barcode', '$ProductDescription', '$SKU', '$CYear', '$HeaderStyle', '$Certification', '$InnerQTY', '$OuterQTY', '$PackagingDescription', '$Comments');";
$result = $conn->query($sql);
if fails echo last error message and comment.
the SepcID may have been set as not null which may cause the problem.
Try not referencing your ID column?
$sql = " INSERT INTO ProductSpecs (Code, ProductName, Barcode, ProductDescription, SKU, CYear, HeaderStyle, Certification, InnerQTY, OuterQTY, PackagingDescription, Comments) VALUES ('$Code', '$ProductName', '$Barcode', '$ProductDescription', '$SKU', '$CYear', '$HeaderStyle', '$Certification', '$InnerQTY', '$OuterQTY', '$PackagingDescription', '$Comments')";
$result = $conn->query($sql)
I have a table with
id - integer AUTO INCREMENT
productid varchar
photo varchar
I use pdo for mysql connection
the code below is giving my an error please any help
$photo = $_POST['photo'];
$product = $_SESSION['prd'];
$todo = $dblink->query("INSERT INTO productphotos VALUES (NULL, '".$product."', '".$photo."'") or die ("Erorr");
Best Reagrds
Thank You
Save yourself the trouble of concatenating values into your SQL and use a prepared statement
$stmt = $dblink->prepare('INSERT INTO productphotos VALUES (NULL, ?, ?)');
$stmt->execute([$product, $photo]);
if(isset($_POST['photo'], $_SESSION['prd'])){
//data
$photo = $_POST['photo'];
$product = $_SESSION['prd'];
$query = "INSERT INTO productphotos VALUES (NULL, :product, :photo)"
$stmt = $dblink->prepare($query);;
$stmt->bindValue(':product', $product, PDO::PARAM_STR);
$stmt->bindValue(':photo', $photo, PDO::PARAM_STR);
$stmt->execute();
}
And you should really make sure you set your connection to throw errors
$dblink->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I'm making a simple sign up/in form for a school assignment.
for some reason I can't get it to create a new column in my current table.
All of the information for the $_Get is coming up properly. I imagine its a syntax error i'm not seeing. Any help would be great. Thank you.
if ( $_GET['action'] == "create" )
{
print('test');
// -----------------------
// PERFORM DATABASE UPDATE
$fn = $_GET['fn'];
$ln = $_GET['ln'];
$id = $_GET['id'];
$user = $_GET['user'];
$tel = $_GET['tel_num'];
$email = $_GET['email'];
$bday = $_GET['birthday'];
$password = $_GET['password'];
$address = $_GET['address'];
print('test1');
mysql_select_db("advweb2");
$sql="INSERT INTO `account` (`user`, `password` , `email` , `first_name` , `last_name` , `address` , `tel_num` , `birthday`)
VALUES ('$user', '$password', '$email', '$fn', '$ln', '$address', '$tel', '$bday')";
print_r($sql);
print("<div style='color:green'>update successful</div>");
// -----------------------
$action = "signin";
}
You need to execute the query.
You should be using MySQLi or PDO as detailed here as mysql_query is deprecated.
Example with mysqli:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$stmt = $mysqli->prepare(
"INSERT INTO `account` (`user`, `password` , `email` , `first_name` , `last_name` , `address` , `tel_num` , `birthday`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
);
$stmt->bind_param('ssssssss', $user, $password, $email, $fn, $ln, $address, $tel, $bday);
$stmt->execute();
/* ... */
$stmt->close()
?>
You need to make sure you clean your $_GET variables before inserting into the database to prevent SQL injection. A good read: how to prevent SQL injection.
Please don't use mysql_query, switch to mysqli or PDO instead.
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
$name = 'one';
$value = 1;
$stmt->execute();
$dbh = null;
Use Mysqli or PDO as explained by others but if you insist execute your query like this:
$sql=mysql_query("INSERT INTO `account` (`user`, `password` , `email` , `first_name` , `last_name` , `address` , `tel_num` , `birthday`)
VALUES ('$user', '$password', '$email', '$fn', '$ln', '$address', '$tel', '$bday')");
Because You prepared query and assigned it to the variable but for missed to execute it.