Failure when inserting data to DB through php - php

So I have this exercise where i need to insert (and do various other actions, i did those successfully) data into a very basic database through php insertion, but I don't seem to be able to do so, and I have absolutely no idea why.
Here is my code (disclaimer, i'm only at the beginning of learning php, so any advice would be really appreciated!):
<?php
include 'Connect.php';
$query = "INSERT INTO game ( product_id, product_name, multiplayer, pegi, genre, release_date, dis_id, dev_name)
VALUES ('"
.$_POST['product_id']."','"
.$_POST['product_name']."','"
.$_POST['multiplayer']."','"
.$_POST['pegi']."','"
.$_POST['genre']."',"
.$_POST['release_date'].",'"
.$_POST['publisher'].",'"
.$_POST['developer']."')";
//execute query
$queryexe = mysql_query($query);
if ($queryexe) {
mysql_query("COMMIT");
print("<p><font size=\"+1\">Success!</font></p>");
} else {
print("<p><font size=\"+1\">Error</font></p>");
}
//disconnect from database
mysql_close($connectionstring);
?>
It connects to the db, as I'm able to see what's in the game table, but i don't know why i'm getting a constant error.
Thanks in advance!

Here is your code modified since that transaction was incomplete
include 'Connect.php';
mysql_query("START TRANSACTION");
$query = "INSERT INTO game ( product_id, product_name, multiplayer, pegi, genre, release_date, dis_id, dev_name)
VALUES ('"
.$_POST['product_id']."','"
.$_POST['product_name']."','"
.$_POST['multiplayer']."','"
.$_POST['pegi']."','"
.$_POST['genre']."','"
.$_POST['release_date']."','"
.$_POST['publisher']."','"
.$_POST['developer']."')";
//execute query
$queryexe = mysql_query($query);
if ($queryexe) {
mysql_query("COMMIT");
print("<p><font size=\"+1\">Success!</font></p>");
} else {
mysql_query("ROLLBACK");
print("<p><font size=\"+1\">Error</font></p>");
}
//disconnect from database
mysql_close($connectionstring);
You were doing a commit, without beggining a transaction, and no rollback in case of mysql error or failure,
As a recommendation, start working with mysqli and don't use your values concatenated in the insert statement.
Edit
You are missing a quote after the double quote in publisher field
.$_POST['release_date'].",'"
.$_POST['publisher']."' // <--- this one

Related

When i inserting data into mysql it insert two datas, and i dont know why

When i inserting using this code it insert two datas and i downt know how to fix it
$sql = "SELECT Version_id FROM versions ORDER BY Version_id DESC LIMIT 1;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$lastVersion =$row["Version_id"];
}
}
echo($lastVersion);
$lastVersion++;
$sql = "INSERT INTO versions (version)
VALUES ('v$lastVersion')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
While I don't exactly understand what you mean with "two datas", I do see multiple issues with your code.
First of all it is horribly inefficient and prone to race conditions. It's also quite wrong, in that it doesn't do what you want it. Not to mention should be replaced with native database functionality.
Most of these can be fixed by simply changing the version_id field to a AUTO_INCREMENT. This will automatically give the new record the next available ID in the set, exactly as what you're trying to do. Then you can retrieve this ID by using "lastInsertId()"
That'll make all of the code in your post superflous, and only require you do do something like this when actually inserting data:
$sql = "INSERT INTO `version`(`setting`, `date`) VALUES (:setting, :date)";
$stmt = $db->prepare ($sql);
$res = $stmt->execute ($data);
$newID = $db->lastInsertId ();
After this the new version ID is stored in the $newID variable.
Of course, if you want to UPDATE the version ID for some reason, then INSERT is the wrong command to use. Also, why use an entire table for what's basically a simple version number? In short, your whole table doesn't make a whole lot of sense for me.
I recommend explaining the rationale behind it, so that we can possibly come up with some better solutions you can use.

Row created in mysql with no error, but no data inserted

Very new at this. I submit my input form, no errors come up. When I go to check the entry into myphpadmin, a row was created, but all the fields are blank.
Not sure what is going on as my text code with only 4 entries works.
<?php
$subscribingcompany= $_POST["subscribingcompany"];
$biztype= $_POST["biztype"];
$sitename= $_POST["sitename"];
$siteadd1= $_POST["siteadd1"];
$city1= $_POST["city1"];
$zip1= $_POST["zip1"];
$state1= $_POST["state1"];
$country1= $_POST["country1"];
$biladd1= $_POST["biladd1"];
$city2= $_POST["city2"];
$zip2= $_POST["zip2"];
$state2= $_POST["state2"];
$country2= $_POST["country2"];
$fename= $_POST["fename"];
$lename= $_POST["lename"];
$email1= $_POST["email1"];
$phone1= $_POST["phone1"];
$foname= $_POST["foname"];
$loname= $_POST["loname"];
$email2= $_POST["email2"];
$phone2= $_POST["phone2"];
$effdate= $_POST["effdate"];
$camquantity= $_POST["camquantity"];
$currency= $_POST["currency"];
$quantity= $_POST["quantity"];
$database="greenguy_cbrsandbox";
$table="DesignPartner";
//Create connection and select database
$con= mysql_connect("example.com", "greenguy_ccb", "password88") or die(mysql_error());
echo "connected";
mysql_select_db("$database", $con) or die(mysql_error());
echo"database found";
//Insert into Table
$insert = "INSERT INTO $table
(id, subscribingcompany, biztype, sitename, siteadd1, city1, zip1, state1, country1, biladd1, city2, zip2, state2, country2, fename, lename, email1, phone1, foname, loname, email2, phone2, effdate, camquantity, currency, quantity)
VALUES
(DEFAULT,'$subscribingcompany','$biztype','$sitename','$siteadd1','$city1','$zip1','$state1','$country1','$biladd1','$city2','$zip2','$state2','$country2','$fename','$lename','$email1','$phone1','$foname','$loname','$email2','$phone2','$effdate','$camquantity','$currency','$quantity')";
$results =mysql_query($insert) or die(mysql_error());
echo"data inserted succesfully";
mysql_close($con);
?>
You Insert query is working properly as you have provided the auto increment functionality
row is getting created but rest of the values are not getting inserted please echo your query during execution .
use echo $insert to know what is getting inserted when query is executing.

add values to mysql database using php on ubuntu

n00b learning php from a book.
I'm trying to add data to a database called adv_php. I'm using the following snippet of code in the page that's receiving the data from the post:
<?php
$dbc = mysqli_connect('host', 'name', 'password', 'adv_php');
if (mysqli_connect_errno())
{
echo "Failed to connec to MySQL" . mysqli_connect_error();
}
$parent_id = $_POST['parent_id'];
$task = $_POST['task'];
// Add the task to the database.
$q = "INSERT INTO (parent_id, task) tasks VALUES ($parent_id,'$task')";
mysqli_query($dbc, $q);
?>
I know this code connects to the database elsewhere as I can retrieve info from the database. With this page, I don't get an error, I just get a blank page, and nothing is added to the database Where am I going wrong?
Your query is wrong...Change it ...
$q = "INSERT INTO tasks(parent_id, task) VALUES ($parent_id,'$task')";
you misplaced table_name, use below query
$q = "INSERT INTO tasks (parent_id, task) VALUES ($parent_id,'$task')";
Your insert statement is wrong
Try this
$q = "INSERT INTO tasks (parent_id, task) VALUES ($parent_id,'$task')";

PHP not Inserting into MySQL database all statements are there

I was wondering if anyone had input as to why this statement isn't inserting into my MySQL database. It's not showing any errors and when I enter the SQL statement in manually it inserts the info.
<?php
$host="mysql16.000webhost.com";
$user_name="a1611480_akaash";
$pwd="*****";
$database_name="a1611480_akaash";
$db=mysql_connect($host, $user_name, $pwd);
$sql = "INSERT INTO mydata VALUES ('dude1', 'dude2', 'dude3', 'dude4', 'dude5')";
mysql_query($sql);
?>
This is due to the fact that mysql does not know which database to use for this SQL statement.
Include mysql_select_db.
mysql_select_db($database_name);
To get any type of error in php (except fatals) enclose your code with a try block
try{
// db code
}catch(Exception $e){
// something is wrong
echo "Oh God! I got this ". $e->getMessage();
}
To see the error do this:
mysql_query($sql) or die("Error:".mysql_error());
And from your query i am assuming that you have one column and you want to add multiple values
So this maybe the format:
$sql = "INSERT INTO mydata VALUES
('dude1'), ('dude2'), ('dude3'), ('dude4'), ('dude5);";
That's because you don't mention the column names - see http://www.w3schools.com/php/php_mysql_insert.asp
Also you forgot to select the database - mysql_select_db("my_db");
So your query would have to be something like "INSERT INTO mydata (column1, column2, column3, column4, column5) VALUES ('dude1', 'dude2', 'dude3', 'dude4', 'dude5')";
Edit: Of course Corey is right. It's just a better practice I think - I always do it :)
You are connecting to a remote host, are you sure you have the rights to do so? Where is this code executed?
Outputting the result of mysql_error() would be useful!

Can not send information from PHP form to multiple mysql database tables

I am trying to insert data into 4 tables ( asset, asset_details, invoice and location). When I submit the form, it tells me that all the data has been submitted successfully but when I check the MySQL database the information is only submitted to the location tables.
Any help will be appreciated, Thank you .
mysql_query("START TRANSITION");
$query1 =("INSERT INTO .asset (asset_tag, asset_number, cap_ex, asset_type_id, invoice_id, status)
Values(".$_POST['asset_tag'] .",,,".$_POST['asset_type'] . ",".$_POST['invoice_number']."," . $_POST['status_id'] .")");
$query2 =("INSERT INTO .asset_details (asset_type_id, asset_tag, asset_type, physical_asset_id, manufacturer, os, os_version, make, model, serial_number, processor, ram, memory, hdd, host_name, notes)
Values(" .",".$_POST['asset_tag']."," .$_POST['asset_type'].",,
,".$_POST['os'].",".$_POST['os_version'].",".$_POST['make'].",".$_POST['model'].",".$_POST['serial_number'].",".$_POST['processor'].",,".$_POST['memory'].",".$_POST['hdd'].",,".$_POST['notes'].")");
$query3 =( "INSERT INTO .invoice (invoice_number, invoice_date, purchas_price, quantity, order_date, vender, warrenty_end, notes)
Values(" .$_POST['invoice_number'].",". $_POST['invoice_date'].",". $_POST['purchase_price'].",,,". $_POST['vender'].")");
$query4 =( "INSERT INTO .location (location_name, rack, row, unit)
Values(" .$_POST['location_name'].",".$_POST['rack'].",".$_POST['row'].",".$_POST['unit'].")");
echo "$query1 $query2 $query3 $query4";
$result1= mysql_query($query1);
$result2= mysql_query($query2);
$result3= mysql_query($query3);
$result4= mysql_query($query4);
$result = mysql_query("COMMIT");
if (!$result)
{
mysql_query("ROLLBACK");
die('Invalid query: ' . mysql_error());
}
else
{
echo "<script>alert('SUCCESS!');</script>";
}
}
mysql_close($con);
?>
There are some strange things;
START TRANSITION should probably be START TRANSACTION.
You're not quoting any of your string values. Strings need to be quoted using ' a'la INSERT INTO TEST VALUES ('olle');
An empty field cannot be indicated by just skipping it, you're doing INSERT INTO TEST (a,b,c) VALUES (1,,2); which is not valid syntax for not setting b.
Also, I recommend using a more modern mysql api than mysql_query, as for example PDO or mysqli, since injecting POST values into a string as you do can be pretty dangerous, you may cause SQL injection problems.
Use '`'s around each attributes(columns) and ''' around each values, it should work
During development, I'd echo each query-expressions before it is sent to the database..
...by the way, mysql_error() is a useful function in php, which returns the last error information of mysql....U may use that for debugging

Categories