I'm having this problem where my database entries are not writing to my table in the correct order. I figured it was because they were entering asynchronously. Therefore, I tried to put them in a function that would synchronize the queries. I came up with the following:
function synchronizedInsert($userID, $pid, $pic, $xCoord, $newLine, $drawingColor)
{
$semRes = sem_get(123321, 1, 0666, 1);
if(sem_acquire($semRes))
{
$sql = "INSERT INTO cbmarker.annot_test (userid, project_id, image, date, coords, newLine, color)
VALUES (" . $userID . "," . $pid . ",'". $pic . "', NOW()," . $xCoord . "," . $newLine . ",'" . $drawingColor . "')";
$result = mysql_query($sql);
sem_release($semRes);
}
}
When I don't use semaphores and have only the query in my function
function synchronizedInsert($userID, $pid, $pic, $xCoord, $newLine, $drawingColor)
{
$sql = "INSERT INTO cbmarker.annot_test (userid, project_id, image, date, coords, newLine, color)
VALUES (" . $userID . "," . $pid . ",'". $pic . "', NOW()," . $xCoord . "," . $newLine . ",'" . $drawingColor . "')";
$result = mysql_query($sql);
}
then the funcion works but the I'm back to the problem of the entries entering in the wrong order. When I add the semaphores, the entries don't enter my table and my console gives me the error "GET ... 500 (Internal Sever Error)". Am I using the semaphores incorrectly or is there something I'm missing. Any help would be appreciated. Thanks.
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 am new to PHP and have done a few tutorials on how to code pages to run code behind. I am having trouble though figuring out why my While loop is only executing a Public Function for the first iteration through the loop. Any ideas?
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$info = array("name" => "", "class" => "", "description" => "", "characteristics" => "");
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
$info[$c] = $data[$c];
}
echo print_r($info);
infoDB::getInstance()->create_record($info[0],$info[1],$info[2],$info[3]);}
The code above prints the $info array for each iteration of the While loop, but the create_record function only inserts the results of the first iteration into the corresponding MYSQL Database. Is there something inherent to the logic in PHP/Instantiation that means it only executes on the first iteration?
Below is the function it is calling to for reference (works correctly for the 1st iteration and then does not recur)
public function create_record ($info, $class, $description, $characteristics) {
$this->query("INSERT INTO tbl_info (toon, zeta, description, characteristics)" . " VALUES ('" . $toon . "', '" . $zeta . "', '" . $description . "', '" . $characteristics . "')");
}
Problem Solved
public function create_record ($info, $class, $description, $characteristics) {
$this->query("INSERT INTO tbl_info (toon, zeta, description, characteristics)" . " VALUES ('" . $toon . "', '" . $zeta . "', '" . $description . "', '" . $characteristics . "')");
}
Is Now
public function create_record ($info, $class, $description, $characteristics) {
$name = $this->real_escape_string($name);
$class = $this->real_escape_string($class);
$description = $this->real_escape_string($description);
$characteristics = $this->real_escape_string($characteristics);
$this->query("INSERT INTO tbl_info (toon, zeta, description, characteristics)" . " VALUES ('" . $toon . "', '" . $zeta . "', '" . $description . "', '" . $characteristics . "')");
}
The query was failing based on something it was reading in from the source spreadsheet needing to be escaped
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);
}
I am trying to loop through a number of results from a form, but can't get it quite right.
for ($i=1;$i<$total;i++)
{
mysql_query("INSERT INTO MYSQL(value1,value2,value3) VALUES('{$i}','{$_POST['$iH']}', '{$_POST['$iA']}'");
}
I want $_POST['$iH'] to be the same as $_POST['1H'],$_POST['2H'], $_POST['3H'] etc.
Like so:
for ($i = 1; $i < $total; $i++) { // <--- You had a typo here
$sql = "INSERT INTO MYSQL(value1,value2,value3) ";
$sql .= "VALUES('{$i}','" . $_POST[$i . 'H'] . "', '" . $_POST[$i . 'A'] . "')";
mysql_query($sql);
}
But, two big problems.
Multiple queries
Boy, what a waste! Dispatch one instead:
$rows = Array();
for ($i = 1; $i < $total; $i++) {
$rows[] = "('{$i}','" . $_POST[$i . 'H'] . "', '" . $_POST[$i . 'A'] . "')";
}
$sql = "INSERT INTO MYSQL(value1,value2,value3) VALUES('" . implode("','", $rows) . "')";
mysql_query($sql);
SQL injection
It continues to baffle me how, in 2011, people are still not getting this.
If you're going to insist upon using the ancient mysql API (not even the OO version?!) rather than PDO, get into the habit of sanitising your inputs:
$rows = Array();
for ($i = 1; $i < $total; $i++) {
$rows[] = "('{$i}'," .
"'" . mysql_escape_string($_POST[$i . 'H']) . "'," .
"'" . mysql_escape_string($_POST[$i . 'A']) . "')";
}
$sql = "INSERT INTO MYSQL(value1,value2,value3) VALUES('" . implode("','", $rows) . "')";
mysql_query($sql);
OK, so without multi-query support in your API it's unlikely to cause you significant grief here, but it can do in authentication routines. Just get used to scripting properly in this regard.
You really need to escape your post variables with mysql_real_escape_string()... you are seriously looking for trouble like that.
In answer to your question, I think you need to do something like this:
mysql_query("INSERT INTO MYSQL(value1,value2,value3) VALUES('{$i}', '" . $_POST[$i . 'H'] . "', '" . $_POST[$i.'A']. "'");
with the letters rubbing up against your variable, the php engine will assume they are part of the variable name; that variable name does not exist, so you will get some strange results.
You need to escape your quotes because your variable is being passed as a literal:
for ($i=1; $i<$total; $i++)
{
mysql_query('INSERT INTO MYSQL(value1,value2,value3) VALUES("' . $i . '","' . $_POST[$i . 'H'] . '", "' . $_POST[$i . 'A'] . '")');
}
i apologize if the question is wrong. i am a still a newbie and a learner however i would appreciate if someone correct me if i am somewhere wrong.
here in the Class method i am using for Inserting the data into the database
public function insert($table,$col,$value)
{
if(is_array($col) && is_array($value))
{
$query = "INSERT INTO ".$table."(" . implode(",",$col) . ") VALUES(" . implode(",",$value) . ")";
}
else
{
$query = "INSERT INTO " . $table . "(" . $col . ") VALUES(". $value . ")";
}
}
now here i am determining if the $col and $value is an array if yes then process it.
however i have a problem here since the VALUES in the Insert statement needs to be represnted in the single or double quote format it will not process the query and hence print the error
for example the below code would print the error
$query = "INSERT INTO users(username,email) VALUES(test,test#test.com)";
and the correct format will be
$query = "INSERT INTO users(username,email) VALUES('test','test#test.com')";
now in the col value i would like to add the single quotes to every value in the array for example the $value array which is like this.
$value = array('test','test#test.com');
should give back the value
'test','test#test.com'
instead of
test,test#test.com
how do i achieve it?
$query = "INSERT INTO $table ('" . implode("','",$col) . "')
VALUES ('" . implode("','",$value) . "')";
Make sure that neither $col nor $value is empty.
Right code:
public function insert($table,$col,$value)
{
if(is_array($col) && is_array($value))
{
$query = "INSERT INTO ".$table."(" . implode(",",$col) . ") VALUES('" . implode("','",$value) . "')";
}
else
{
$query = "INSERT INTO " . $table . "(" . $col . ") VALUES('". $value . "')";
}
}
CHANGE:
VALUES(" . implode(",",$value) . ")
TO
VALUES('" . implode("','",$value) . "')
(Your output:)
VALUES(demo,demo2)
(New Output:)
VALUES('demo','demo2')
you could do this?
$value = array("'test'","'test#test.com'");
You can use array_map() method:
function addQuotes($str)
{
return "'".$str."'";
}
$value = array_map("addQuotes", $value);
or follow a Oswald's answer recommendations.