Different from this question, but similar in that I don't get an error when adding information to my database.
$sql = "INSERT INTO 'nlcc_ver1'.'tUsers' ('userID', 'userName', 'userPassword', 'userHash',
'user_first_name', 'user_last_name', 'user_corps', 'is_admin', 'is_trg', 'is_sup', 'is_co')
VALUES (NULL, '" . $userName . "', '" . $hash . "', '" . $salt . "', '" . $f_name . "', '" .
$l_name . "', '" . $corps . "', '" . $admin . "', '" . $trg . "', '" . $sup . "', '" . $co . "')";
$hostname_Database = "localhost";
$database_Database = "nlcc_ver1";
$username_Database = "root";
$password_Database = "";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli_query($mysqli, $sql);
echo "Query run. Inserted UserID " . mysqli_insert_id($mysqli) . "<br />";
Line breaks inserted to avoid sideways scrolling... It says on the web page that mysqli_insert_id($mysqli) is 0, and nothing is added to the table on my database. I do not see an error connecting to the database appearing, and MySQL is running on my server, and phpinfo() shows both the MySQL and MySQLI extension loaded. This is just a development machine, so don't worry about the security (i.e. no password). I have tried googling the problem, but am not finding too much. I don't know about object oriented PHP programming with ->, I am used to using _. Is this method still supported?
You've mixed procedural and object-oriented MySQLi styles. This has led to you trying to use the functions like mysqli_query($mysqli) instead of the member functions like $mysqli->query(). Your $mysqli is an object, not a resource handle.
And, you're not performing any error checking on your query. If you were, you'd see that you have mistakenly used single quotes to delimit table and field names, not backticks.
$sql = "INSERT INTO `nlcc_ver1`.`tUsers`
(`userID`, `userName`, `userPassword`, `userHash`,
`user_first_name`, `user_last_name`, `user_corps`,
`is_admin`, `is_trg`, `is_sup`, `is_co`)
VALUES (NULL, '" . $userName . "', '" . $hash . "', '" . $salt . "', '" .
$f_name . "', '" . $l_name . "', '" . $corps . "', '" . $admin .
"', '" . $trg . "', '" . $sup . "', '" . $co . "')";
$hostname_Database = "localhost";
$database_Database = "nlcc_ver1";
$username_Database = "root";
$password_Database = "";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query($sql);
if (!$result) {
printf("%s\n", $mysqli->error);
exit();
}
echo "Query run. Inserted UserID " . $mysqli->insert_id . "<br />";
I strongly suggest using the manual as your reference. It's quite clear on how to use these functions when you're using either procedural or object-oriented style MySQLi.
$mysqli_query($mysqli, $sql);
should be
mysqli_query($mysqli, $sql);
OR
$mysqli->query($sql);
AND later on
$mysqli->insert_id();
Look at this:
'nlcc_ver1'.'tUsers'
You have to use backticks here as quote character:
`nlcc_ver1`.`tUsers`
But however(assuming that the $ in $mysqli_query is just a typo): You will not get errors for the query , unless you use mysqli_error() right after executing the query.
SET AutoCommit = 1 before inserting
$mysqli->query('SET AUTOCOMMIT = 1');
Related
I have a PHP and I want to do 2 inserts and 1 delete, but I can only make an insert. If the array containt the last parameter == "historico" should delete from instant_table all register with same serial_num and inserte the array intro the instant_table and insert in historical_table("SensorData"). Ifnot (the array don't hace the parameter "historico"), should de delete from instant_table all register with same serial_num and only inserte the array intro the instant_table.
My code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$serial_numb = test_input($_POST["serial_numb"]);
$DHTtempC = test_input($_POST["DHTtempC"]);
$DHThumid = test_input($_POST["DHThumid"]);
$CCS811_CO2 = test_input($_POST["CCS811_CO2"]);
$CCS811_tVOC = test_input($_POST["CCS811_tVOC"]);
$PM25 = test_input($_POST["PM25"]);
$PM10 = test_input($_POST["PM10"]);
$reading_date = date("Y-m-d");
$update_status = test_input($_POST["update_status"]);
$tipo_tabla = test_input($_POST["tipo_tabla"]);
// Create connection
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
if ($tipo_tabla == "historico"){
$sql = "INSERT INTO SensorData (serial_numb, DHTtempC, DHThumid, CCS811_CO2, CCS811_tVOC, PM25, PM10, reading_date, update_status)
VALUES ('" . $serial_numb . "', '" . $DHTtempC . "', '" . $DHThumid . "', '" . $CCS811_CO2 . "', '" . $CCS811_tVOC . "', '" . $PM25 . "', '" . $PM10 . "', '" . $reading_date . "', '" . $update_status . "')";
}
$sql = "DELETE FROM instant_data WHERE (serial_numb = '" . $serial_numb . "')";
$sql = "INSERT INTO instant_data (serial_numb, DHTtempC, DHThumid, CCS811_CO2, CCS811_tVOC, PM25, PM10, reading_date, update_status)
VALUES ('" . $serial_numb . "', '" . $DHTtempC . "', '" . $DHThumid . "', '" . $CCS811_CO2 . "', '" . $CCS811_tVOC . "', '" . $PM25 . "', '" . $PM10 . "', '" . $reading_date . "', '" . $update_status . "')";
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$mysqli->close();
}
else {
echo "No data posted with HTTP POST.";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Tu sum up, If the array contains the parameter, INSERTE(TABLE1) + DELETE with same serial_num(TABLE2) + INSERTE(TABLE2). If not DELETE with same serial_num(TABLE2) + INSERTE(TABLE2).
EDIT: Now this code only make the second INSERT
It seems like you are overwriting the content of $sql without executing the queries in between. You have to either:
execute each query before redefining $sql
use $sql .= (instead of $sql =) to concatenate the next query. If you do this, you have to terminate your sql query with an ; before concatenating the next query.
Are you using this code just for an small personal project or are you going to publish this in any way? In case of the later one:
please read into PHP SQL best practices. With your current approach you are vulnerable to SQL injections and your code is kinda difficult to read.
I`m stuck for some time to fix this trouble. I followed this article https://www.sitepoint.com/creating-a-scrud-system-using-jquery-json-and-datatables/
to create SCRUD System. But I stuck when I need to add a new record to PostgreSQL.
The working MySQL part of the code is:
$db_server = 'localhost';
$db_username = 'root';
$db_password = '123456';
$db_name = 'test';
$db_connection = mysqli_connect($db_server, $db_username, $db_password, $db_name);
$query = "INSERT INTO it_companies SET ";
if (isset($_GET['rank'])) { $query .= "rank = '" . mysqli_real_escape_string($db_connection, $_GET['rank']) . "', "; }
if (isset($_GET['company_name'])) { $query .= "company_name = '" . mysqli_real_escape_string($db_connection, $_GET['company_name']) . "', "; }
if (isset($_GET['industries'])) { $query .= "industries = '" . mysqli_real_escape_string($db_connection, $_GET['industries']) . "', "; }
if (isset($_GET['revenue'])) { $query .= "revenue = '" . mysqli_real_escape_string($db_connection, $_GET['revenue']) . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "fiscal_year = '" . mysqli_real_escape_string($db_connection, $_GET['fiscal_year']) . "', "; }
if (isset($_GET['employees'])) { $query .= "employees = '" . mysqli_real_escape_string($db_connection, $_GET['employees']) . "', "; }
if (isset($_GET['market_cap'])) { $query .= "market_cap = '" . mysqli_real_escape_string($db_connection, $_GET['market_cap']) . "', "; }
if (isset($_GET['headquarters'])) { $query .= "headquarters = '" . mysqli_real_escape_string($db_connection, $_GET['headquarters']) . "'"; }
$query = mysqli_query($db_connection, $query);
I managed to write this and it fails to work for PostgreSQL:
$conn_string = "dbname=test user=postgres password=123456";
$query = "INSERT INTO it_companies VALUES ";
if (isset($_GET['rank'])) { $query .= "('" . pg_escape_string($db_connection, $_GET['rank']) . "', "; }
if (isset($_GET['company_name'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['company_name']) . "', "; }
if (isset($_GET['industries'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['industries']) . "', "; }
if (isset($_GET['revenue'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['revenue']) . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['fiscal_year']) . "', "; }
if (isset($_GET['employees'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['employees']) . "', "; }
if (isset($_GET['market_cap'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['market_cap']) . "', "; }
if (isset($_GET['headquarters'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['headquarters']) . "');"; }
$query = pg_query($db_connection, $query);
The message I gets from the system is: "Add request failed: parsererror"
The Edit and remove functions are working well.
I follow to build this clause from the PGSQL site example:
INSERT INTO films VALUES
('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes');
Any what I`m doing wrong? Thanks!
UPDATE
The echo of the query and the error was the id column. In Mysql code there was no problem with the ID colum. Why when i use pgsql it does?:
INSERT INTO it_companies (rank,company_name,industries,revenue,fiscal_year,employees,market_cap,headquarters)
VALUES ('1', 'asd', 'asd', '1', '2000', '2', '3', 'asdf');
Warning: pg_query(): Query failed: ERROR: duplicate key value violates unique constraint "it_companies_pkey" DETAIL: Key (company_id)=(2) already exists. in C:\WEB\Apache24\htdocs\datatableeditor\data.php on line 121
{"result":"error","message":"query error"
,"data":[]}
UPDATE2
The working code with one bug:
$query = "INSERT INTO it_companies (rank,company_name,industries,revenue,fiscal_year,employees,market_cap,headquarters) VALUES ";
if (isset($_GET['rank'])) { $query .= "('" . $_GET['rank'] . "', "; }
if (isset($_GET['company_name'])) { $query .= "'" . $_GET['company_name'] . "', "; }
if (isset($_GET['industries'])) { $query .= "'" . $_GET['industries'] . "', "; }
if (isset($_GET['revenue'])) { $query .= "'" . $_GET['revenue'] . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "'" . $_GET['fiscal_year'] . "', "; }
if (isset($_GET['employees'])) { $query .= "'" . $_GET['employees'] . "', "; }
if (isset($_GET['market_cap'])) { $query .= "'" . $_GET['market_cap'] . "', "; }
if (isset($_GET['headquarters'])) { $query .= "'" . $_GET['headquarters'] . "') RETURNING company_id;"; }
echo $query;
After this query, the message "Add request failed: parsererror" is still there. But after a manual refresh of the page, the new data is saved. Any idea why this message apears and not loading the data automatically?
UPDATE 3 - Success
I forgot to remove echo $query; from the code causing the error message.
All works now. Thanks for the help to all! :)
You need a little more work in your query string building.
You only add the open parenthesis ( if rank is present
You only add the closing parenthesis ) if headquarters is present.
Also you need specify what field column get which value, otherwise you end with headquarter name into the fiscal_year field. If columns are not specified the values are add it on the same order as define on the table.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
And as other have comment check the $query to see what you have.
Here is my code, it works and no errors pop up and the correct data for the variables are there.
When it's all done it shows Done for the last echo.
However, when I go into heidisql to view the database table, nothing has changed, even when I run the query in heidisql, still same results.
// Make connection to database
$connection = mysqli_connect($host,$user,$pass,$dbnm);
// Make query
$myQuery = "
UPDATE Ekhaya_Inventory SET
ekhaya_inventory_stock_item = '" . $stockItemPost . "',
ekhaya_inventory_stock_left = '" . $stockLeftPost . "',
ekhaya_inventory_stock_out = '" . $stockOutPost . "',
ekhaya_inventory_stock_minimum = '" . $stockMinimumPost . "',
ekhaya_inventory_stock_price_per_item = '" . $stockPricePIPost . "',
ekhaya_inventory_value_of_stock_left = '" . $stockValueOfStockLeftPost . "'
WHERE
ekhaya_inventory_stock_code = '" . $stockCodePost . "'
AND
ekhaya_inventory_stock_code = '" . $stockLocationPost . "'
";
mysqli_query($connection,$myQuery)or die("Error: ".mysqli_error($connection));
mysqli_close($connection)or die("Error: ".mysqli_error($connection));
echo "<br>Done";
WHERE
ekhaya_inventory_stock_code = '" . $stockCodePost . "'
AND
ekhaya_inventory_stock_code = '" . $stockLocationPost . "'
it is wrong because one field can`t contain two different values in the same time
This is my first attempt at creating a form. When I click submit no record is added to the table.
What am I not understanding here? (I don't just want the answer!)
<?php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (
isset($_POST['store_id']) &&
isset($_POST['item_title']) &&
isset($_POST['date']) &&
isset($_POST['price'])
)
{
$store = get_post('store_id');
$item = get_post('item_title');
$date = get_post('date');
$price = get_post('price');
$query = "INSERT INTO competitors VALUES('$store', '$item', '$date', '$price')";
if(!mysql_query($query, $db_server))
echo "INSERT failed: $query<br/>" .
mysql_error() . "<br/><br/>";
}
?>
1) you need to switch to PDO or MySQLi. These routines are deprecated.
2) try changing your $query to
$query = "INSERT INTO competitors VALUES('" . $store. "', '" . $item . "', '" . $date . "', '" . $price . "')";
3) read up on prepared statements. This approach leaves you open to injection attacks.
I'm using this example: www.jtable.org
I've downloaded the jTable PHP version. I then edited the script. The jTable simple version is working, but my edited version isn't.
I can create a list, but I can't add a row; this code is causing problems. However, PHP doesn't display any error messages.
else if($_GET["action"] == "create")
{
//Insert record into database
$result = mysql_query("INSERT INTO veriler(bolge, sehir, firma, adres, tel, web) VALUES('" . $_POST["bolge"] . "', '" . $_POST["sehir"] . "', '" . $_POST["firma"] . "', '" . $_POST["adres"] . "', '" . $_POST["tel"] . "', '" . $_POST["web"] . "'");
//Get last inserted record (to return to jTable)
$result = mysql_query("SELECT * FROM veriler WHERE id = LAST_INSERT_ID();");
$row = mysql_fetch_array($result);
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Record'] = $row;
print json_encode($jTableResult);
}
What is the problem?
In this line, there is a problem:
$result = mysql_query("INSERT INTO veriler(bolge, sehir, firma, adres, tel, web) VALUES('" . $_POST["bolge"] . "', '" . $_POST["sehir"] . "', '" . $_POST["firma"] . "', '" . $_POST["adres"] . "', '" . $_POST["tel"] . "', '" . $_POST["web"] . "'");
The format for the INSERT query is:
INSERT INTO table (column1, column2, etc) VALUES (value1, value2, etc);
You missed a closing parenthesis for the VALUES part.
To improve your code, you can do something like this:
$result = mysql_query("YOUR QUERY") or die('ERROR: '.mysql_error());
And please read on SQL Injection.
here is the problem you forget the )
$result = mysql_query("INSERT INTO veriler(bolge, sehir, firma, adres, tel, web)
VALUES('" . $_POST["bolge"] . "', '" . $_POST["sehir"] . "', '" . $_POST["firma"] . "', '" . $_POST["adres"] . "', '" . $_POST["tel"] . "', '" . $_POST["web"] . "'");
use
$result = mysql_query("INSERT INTO veriler(bolge, sehir, firma, adres, tel, web) VALUES
('{$_POST["bolge"]}', '{$_POST["sehir"] }' , '{$_POST["firma"]}' , '{$_POST["adres"] }', '{$_POST["tel"]}', '{$_POST["web"]}' )" ) ;
first of all you can reduce one query of last_inset_id()
else if($_GET["action"] == "create")
{
//Insert record into database
$result = mysql_query("INSERT INTO veriler(bolge, sehir, firma, adres, tel, web) VALUES('" . $_POST["bolge"] . "', '" . $_POST["sehir"] . "', '" . $_POST["firma"] . "', '" . $_POST["adres"] . "', '" . $_POST["tel"] . "', '" . $_POST["web"] . "'"));
//Get last inserted record (to return to jTable)
//check youe result query you are missing something here
$id=mysql_insert_id();
//this will automatically give you last id
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['id'] = $id;
$jTableResult['Record'] = $row;
$jTableResult['aderes'] = $_POST['adres'];
//and so on
print json_encode($jTableResult);
}