How to resolve problem with unique id PHP, ORACLE 12C - php

Using PHP + Oracle 12c
I'm trying to insert many rows but i got an error "oci_execute(): ORA-00001: unique constraint (S95417.FIRMA__IDX)" This is strange for me because in loop i'm getting last id and incrementing it.
I used debbuger and (On INSERT) i'm getting last id but incrementing is not working.
Could you tell me why?
Data which i added
INSERT INTO FIRMA VALUES(18,MICROSOFT,2432213715,2020-03-26,23)
INSERT INTO FIRMA VALUES(19,APPLE,7512202082,2020-03-26,42)
SELECT NVL(MAX(firmaid),0)+1
I made code very similar using that for other tables and it's working fine.
My code:
$ile_razy = $_POST['liczba_powtorzen'];
$firma = "SELECT * FROM FIRMA";
$c = oci_connect($username, $password, $database);
if (!$c) {
$m = oci_error();
trigger_error('Could not connect to database: '. $m['message'], E_USER_ERROR);
}
$file = 'firma.txt';
$current = file_get_contents($file);
for ($i = 1; $i <= $ile_razy; $i++) {
$nazwa = randCompanyName();
$nip = randNIP();
$dataWspolpracy = date("Y-m-d");
$ids_array = array();
$adresid = "SELECT adresid FROM ADRES";
$stmtt = oci_parse($c, $adresid);
$result = oci_execute($stmtt);
while($row = oci_fetch_array($stmtt))
{
$ids_array[] = $row['ADRESID'];
}
$randIndex = array_rand($ids_array);
$adresId = $ids_array[$randIndex];
// HERE IS PROBLEM
$firmaQuery = "INSERT INTO FIRMA SELECT NVL(MAX(firmaid),0) + 1,'$nazwa', '$nip', '$dataWspolpracy', '$adresId' from FIRMA";
$ex = oci_parse($c,$firmaQuery);
// "zapytanie" is working fine
$zapytanie = "SELECT NVL(MAX(firmaid),0)+1 from FIRMA";
$stmt = oci_parse($c, $zapytanie);
$results = oci_execute($stmt);
while($row = oci_fetch_assoc($stmt)){
$rowid = $row["NVL(MAX(FIRMAID),0)+1"];
}
$firmaIdForTxt = "INSERT INTO FIRMA VALUES(".$rowid.",".$nazwa.",".$nip.",".$dataWspolpracy.",".$adresId.")";
echo $rowid. ", ";
oci_execute($ex);
$current .= $i. ".".$firmaIdForTxt."\n";
file_put_contents($file, $current);
}
In my db
I have changed that but error still appears

You can make your FIRMAID an identity column : Oracle will handle the increment internally, and it is much more safer for your data.
Then you can insert your data with this query :
INSERT INTO FIRMA(nazwa, nip, datawspolpracy, adresid) VALUES('$nazwa', '$nip', '$dataWspolpracy', '$adresId')
NOTE : this is for a quick answer, for a safer solution and avoid SQL injections, use prepared statements : PHP oci examples (See example #2)

Related

Dynamic value in sql query using php

I want to search a certain string in all the columns of different tables, so I am looping the query through every column name. but if i give it as dynamic value it does not seem to work.
what is wrong?
<?php
$search = $_POST['search'];
$columns = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'feedback'";
$columns_result = $conn->query($columns);
$columns_array = array();
if (!$columns_result) {
echo $conn->error;
} else {
while ($row = $columns_result->fetch_assoc()) {
//var_dump($row);
//echo $row['COLUMN_NAME']."</br>";
array_push($columns_array, $row['COLUMN_NAME']);
}
}
var_dump($columns_array);
$row_result = array();
for ($i = 0; $i < count($columns_array); $i++) {
echo $columns_array[$i] . "</br>";
$name = "name";
// $sql = 'SELECT * FROM feedback WHERE "'.$search.'" in ("'.$columns_array[$i].'")';
$sql = 'SELECT * FROM feedback WHERE ' . $name . ' like "' . $search . '"';
$result = $conn->query($sql);
if (!$result) {
echo "hi";
echo $conn->error;
} else {
foreach ($result as $row) {
array_push($row_result, $row);
echo "hey";
}
}
}
var_dump($row_result);
I am getting the column names of the table and looping through them because I have so many other tables which I need to search that given string. I don't know if it is optimal I did not have any other solution in my mind. If someone can tell a good way I will try that.
It looks to me that you want to generate a where clause that looks at any available nvarchar column of your table for a possible match. Maybe something like the following is helpful to you?
I wrote the following with SQL-Server in mind since at the beginning the question wasn't clearly tagged as MySql. However, it turns out that with a few minor changes the query work for MySql too (nvarchar needs to become varchar):
$search='%';$tbl='feedback';
if (isset($_POST['search'])) $search = $_POST['search'];
$columns = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '$tbl' AND DATA_TYPE ='nvarchar'";
$columns_result = $conn->query($columns);
$columns_array = array();
if(!$columns_result) print_r($conn->errorInfo());
else while ($row = $columns_result->fetch(PDO::FETCH_ASSOC))
array_push($columns_array, "$row[COLUMN_NAME] LIKE ?");
$where = join("\n OR ",$columns_array);
$sth = $conn->prepare("SELECT * FROM $tbl WHERE $where");
for ($i=count($columns_array); $i;$i--) $sth->bindParam($i, $search);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
The above is a revised version using prepared statements. I have now tested this latest version using PHP 7.2.12 and SQL-Server. It turned out that I had to rewrite my parameter binding part. Matching so many columns is not a very elegant way of doing queries anyway. But it has been a nice exercise.
It looks like you are using mysqli, so I wanted to give another way of doing it via mysqli.
It does more or less the same as cars10m solution.
$search = $_POST['search'];
$columns = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'feedback'";
$columns_result = $conn->query($columns)->fetch_all(MYSQLI_ASSOC);
// Here dynamically prepare WHERE with all the columns joined with OR
$sql = 'SELECT * FROM feedback WHERE ';
$arrayOfWHERE = [];
foreach($columns_result as $col){
$arrayOfWHERE[] = '`'.$col['COLUMN_NAME'].'` LIKE ?';
}
$sql .= implode(' OR ', $arrayOfWHERE);
// prepare/bind/execute
$stmt = $conn->prepare($sql);
$stmt->bind_param(str_repeat("s", count($arrayOfWHERE)), ...array_fill(0, count($arrayOfWHERE), $search));
$stmt->execute();
$result = $stmt->get_result();
$row_result = $result->fetch_all(MYSQLI_ASSOC);
var_dump($row_result);
Of course this will search for this value in every column of the table. It doesn't consider data type. And as always I have to point out the using PDO is better than mysqli. If you can switch to PDO.

Copy 1 sql table to another with some additional data

I have this code:
<?php
//MYSQL
$dbserver="..."; //adresa MySQL
$dblogin="..."; //jméno uživatele MySQL
$dbheslo="..."; //heslo MySQL
$dbnazev="..."; //název databáze MySQL
$mysqli = new mysqli($dbserver, $dblogin, $dbheslo, $dbnazev);
if ($mysqli->connect_error) {
die('Nepodařilo se připojit k MySQL serveru (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$mysqli->query("SET NAMES 'utf8'"); // nastavíme kódování MySQL
while($row = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL")->fetch_assoc()){
$tempid = $row['tempid'];
$jmeno = $row['jmeno'];
$prijmeni = $row['prijmeni'];
$email = $row['email'];
$bydliste = $row['bydliste'];
$souhlas = "on";
$aktuality = "on";
$timestamp = time();
$hash = md5("77c0a83besxxxcg1a190ab90d".time().$tempid.rand(10000000, 99999999));
$poznamky = "import19052018";
$vloz ="INSERT into `potvrzenotest` set jmeno='".$jmeno."', prijmeni='".$prijmeni."', bydliste='".$bydliste."', email='".$email."', souhlas='".$souhlas."', aktuality='".$aktuality."', timestamp='".$timestamp."', hash='".$hash."', poznamky='".$poznamky."';";
$result=$mysqli->query($vloz);
$cas = date('H:i');
echo '['.$cas.'] ID '.$tempid.' imported.', PHP_EOL;
}
mysqli_close($mysqli); .
?>
I have one table with some data and I have to copy it to another table with some additional data (like hash etc.).
When I run the code above, I got this:
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
So, only 1 row is being copied.
Could you please help me, where is the problem?
while($row = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL")->fetch_assoc()){ ... }
This loop will never end. And it will fetch the first row again and again.
You should execute the query outside the loop:
$selectResult = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL");
while ($row = $selectResult->fetch_assoc()) { ... }
As a side note: Consider to use a prepared statement for your INSERT statement in the loop. This will prevent SQL syntax errors if some of the values may contail special characters like '. If you run them in one transaction, you might even improve the performance.

Update multiple rows in single query php mysql

I am trying to update multiple rows in a single query. Data doesnt get updated in my code. I am trying to join the two tables. When user enters a no. The data from the 2 tables will be displayed which is connected through the foreign key.The data from the table1 gets updated. Where as the columns from the table 2 doesnt get updated. I need to update the second table based on unique id
if($_REQUEST["profile"] == "profile")
{
$Id = $_REQUEST["id"];
$firstname = mysql_real_escape_string($_REQUEST["firstname"]);
$serial = mysql_real_escape_string($_REQUEST["serial"]);
$dom = mysql_real_escape_string($_REQUEST["dom"]);
$idno = $_REQUEST["idno"];
$pow = mysql_real_escape_string(stripslashes($_REQUEST["pow"]));
$address = mysql_real_escape_string(stripslashes($_REQUEST["address"]));
$bookno = mysql_real_escape_string(stripslashes($_REQUEST["bookno"]));
$zone = mysql_real_escape_string(stripslashes($_REQUEST["zone"]));
$mobile = mysql_real_escape_string(stripslashes($_REQUEST["phone"]));
$phone = mysql_real_escape_string(stripslashes($_REQUEST["mobile"]));
$mothertongue=mysql_real_escape_string(stripslashes($_REQUEST["mothertongue"]));
$nof=mysql_real_escape_string(stripslashes($_REQUEST["nof"]));
$email=mysql_real_escape_string(stripslashes($_REQUEST["email"]));
$nom=$_REQUEST["nom"];
$nofemale=$_REQUEST["nofemale"];
mysql_query("UPDATE profile SET firstname='".$firstname."',serial='".$serial."',dom='".$dom."',idno='".$idno."',pow='".$pow."',address='".$address."',bookno='".$bookno."',
zone='".$zone."',phone='".$mobile."',mobile='".$phone."',mothertongue='".$mothertongue."',email='".$email."',nof='".$nof."',nom='".$nom."',nofemale='".$nofemale."' WHERE id = '".$_POST['id']."' " ) or die(mysql_error());
for($i=0;$i<count($_REQUEST['slno1']);$i++)
{
$mid=$_REQUEST['mid'][$i];
$slno1 = mysql_real_escape_string(stripslashes($_REQUEST["slno1"][$i]));
$name1 = mysql_real_escape_string(stripslashes($_REQUEST["name1"][$i]));
$rhof1 = mysql_real_escape_string(stripslashes($_REQUEST["rhof1"][$i]));
$dob1 = mysql_real_escape_string(stripslashes($_REQUEST["dob1"][$i]));
$dobapt1 = mysql_real_escape_string(stripslashes($_REQUEST["dobapt1"][$i]));
$doc1 = mysql_real_escape_string(stripslashes($_REQUEST["doc1"][$i]));
$doconf1 = mysql_real_escape_string(stripslashes($_REQUEST["doconf1"][$i]));
$qualification1 = mysql_real_escape_string(stripslashes($_REQUEST["qualification1"][$i]));
$school1 = mysql_real_escape_string(stripslashes($_REQUEST["school1"][$i]));
$occupation1 = mysql_real_escape_string(stripslashes($_REQUEST["occupation1"][$i]));
$run=mysql_query("UPDATE member SET
slno1='".$slno1."',name1='".$name1."',rhof1='".$rhof1."',dob1='".$dob1."',dobapt1='".$dobapt1."',doc1='".$doc1."',doconf1='".$doconf1."',qualification1='".$qualification1."' WHERE mid = '".$mid."' " ) or die(mysql_error());
}
}
Please use PDO so you won't have to escape strings and so your code gets simpler to read. Your query has too many quotes used and this alone can make it easy to fail. Please use following examples and this should help you succeed.
Basic PDO update:
https://www.w3schools.com/php/php_mysql_update.asp
Bind Params:
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
In your query you are using $_POST['mid'] instead of that you should use $mid which you are already reading as
$mid=$_REQUEST['mid'][$i];
As per my understanding UPDATE query is used to update a limited number of records if using the where condition. So the only way that I can think of is using an INSERT query with ON DUPLICATE KEY UPDATE clause. Try the below code:
for($i=0;$i<count($_REQUEST['mid']);$i++) {
$mid[] = $_REQUEST['mid'][$i];
$slno1[] = mysql_real_escape_string(stripslashes($_REQUEST["slno1"][$i]));
$name1[] = mysql_real_escape_string(stripslashes($_REQUEST["name1"][$i]));
$rhof1[] = mysql_real_escape_string(stripslashes($_REQUEST["rhof1"][$i]));
$dob1[] = mysql_real_escape_string(stripslashes($_REQUEST["dob1"][$i]));
$dobapt1[] = mysql_real_escape_string(stripslashes($_REQUEST["dobapt1"][$i]));
$doc1[] = mysql_real_escape_string(stripslashes($_REQUEST["doc1"][$i]));
$doconf1[] = mysql_real_escape_string(stripslashes($_REQUEST["doconf1"][$i]));
$qualification1[] = mysql_real_escape_string(stripslashes($_REQUEST["qualification1"][$i]));
$school1[] = mysql_real_escape_string(stripslashes($_REQUEST["school1"][$i]));
$occupation1[] = mysql_real_escape_string(stripslashes($_REQUEST["occupation1"][$i]));
}
$query = "INSERT INTO `member` (`mid`,`slno1`,`name1`,`rhof1`,`dob1`,`dobapt1`,`doc1`,`doconf1`,`qualification1`) VALUES ";
for ($i = 0; $i < count($mid); $i++) {
$query .= "('".$mid[$i]."','".$slno1[$i]."','".$name1[$i]."','".$rhof1[$i]."','".$dob1[$i]."','".$dobapt1[$i]."','".$doc1[$i]."','".$doconf1[$i]."','".$qualification1[$i]."')";
if ($i != (count($mid) - 1)) {
$query .= ',';
}
}
$query .= ' ON DUPLICATE KEY UPDATE `slno1` = VALUES(`slno1`), `name1` = VALUES(`name1`), `rhof1` = VALUES(`rhof1`), `dob1` = VALUES(`dob1`), `dobapt1` = VALUES(`dobapt1`), `doc1` = VALUES(`doc1`), `doconf1` = VALUES(`doconf1`), `qualification1` = VALUES(`qualification1`);';
$run=mysql_query($query) or die(mysql_error());
Hope This Helps.

php visitor counter not working

I am having a problem with mysql. My php code is not working.
<?php
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
$find_counts = mysql_query("SELECT * FROM user_count");
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE 'visitor_counter' . 'user_count' SET
'counts'=$new_count");
}
?>
I have tested putting some echo on my codes. Once i put the echo code on the while loop the echo doesnt work. Can anyone help me.
Try this :
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
$find_counts = mysql_query("SELECT * FROM user_count");
$current_count = 0;
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
}
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE 'visitor_counter' . 'user_count' SET
'counts'=$new_count");
Check if your SELECT query works by change the code:
mysql_query("SELECT * FROM user_count") or die(mysql_error());
Check if there is data in de table user_count and edit the query:
while($row = mysql_fetch_assoc($find_counts))
{
print_r($row); //to print the database row
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE user_count SET counts=".$new_count); // no need to specify the database, you already did with mysql_select_db.
}
Dont need to specify DB, and quotes are wrong, change to:
$update_count = mysql_query("UPDATE user_count SET counts = $new_count");
You also might want to specify a page:
$update_count = mysql_query("UPDATE user_count SET counts = $new_count WHERE page = '$this_page'");
what are you trying here ?
mysql_query("UPDATE 'visitor_counter' . 'user_count' SET 'counts'=$new_count");
whats the table name ?
i guess your tablename is user_count
or do you have more than one tablename you like to update ?!?!?
if tablenam eis user_count it should look like
$update_count = mysql_query("UPDATE user_count SET counts={$new_count}");
so the total while would be
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE user_count SET counts={$new_count}");
}
Important
Dont use
'tablename'
in your sql query... if you like to declair a tablename use
`tablename`
Use single query:
UPDATE `visitor_counter`.`user_count` SET `counts`=`counts`+1;
then do your SELECT ... FROM
because passing variable into sql query for this kind of operations are not always safe
and here is Your code:
<?php
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
mysql_query("UPDATE `visitor_counter`.`user_count` SET `counts`=`counts`+1");
$counts = array();
$result = mysql_query("SELECT * FROM user_count");
while($data = mysql_fetch_assoc($result)) {
$counts[$data['id']] = $data['counts'];
}
?>
I'm really surprised to see everybody here posts code using the old and deprecated mysql functions (although some of them stated this is wrong). I would like to advice you AGAINST using mysql functions - they are deprecated as of version 5.5. You should use either mysqli or PDO instead. In my opinion, you should be using PDO as it provides support for almost all databases and you could use prepared statements.
Now to your code - I'm not quite sure why would use a cycle to count all of the records in the counts column. A much better way to do this is by using atomic increment - it will also guarantee your counter is properly incremented in case two queries are trying to increment the value simultaneously. Although you haven't posted your table structure, I believe something like this should do the work:
<?php
// Database connection settings
$db_host = '127.0.0.1';
$db_name = 'visitor_counter';
$db_user = 'root';
$db_pass = 'root';
// Try to connect to the database
try {
$dsn = 'mysql:host='.$db_host.';dbname='.$db_name;
$db = new PDO($dsn, $db_user, $db_pass);
} catch ( PDOException $e ){
// Do something if connection could not be established
throw new ErrorException("Could not connect to database!",0,1,__FILE__,__LINE__,$e);
}
// Find counts
// Assuming you have a user_id column in your `user_count` table.
$user_id = 1;
// Update counter
$update = $db->prepare('UPDATE user_count SET counter=(counter+1) WHERE user_id = :user_id');
$update->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$update->execute();
?>
P.S. In this code I'm assuming you're saving the visitor counter in the user_count.counter column and whenever somebody visits that user, the counter column is incremented for that specific user, rather than updating the counter for all users (as your code suggests).

MySQL PHP SELECT throwing up an error?

I am trying to make a comment section on my hand made site, using PHP and MySQL. I have got the comments stored in my database, but when I try to SELECT them my site throws up this error,
mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 9 in /home/a9210109/public_html/comments.php on line 16
My code so far is below
<?php
$comment = $_POST['comment'];
$mysql_host = "";
$mysql_database = "";
$mysql_user = "";
$mysql_password = "";
mysql_connect($mysql_host,$mysql_user,$mysql_password);
#mysql_select_db($mysql_database) or die( "Unable to select database");
$CreateTable = "CREATE TABLE comments (comment VARCHAR(255), time VARCHAR(255));";
mysql_query($CreateTable);
$UseComment = "INSERT INTO comments VALUES ('$comment')";
mysql_query($UseComment);
$SelectComments = "SELECT * FROM comments";
$comments = mysql_query($SelectComments);
$num=mysql_numrows($comments);
$variable=mysql_result($comments,$i,"comment");
mysql_close();
?>
Show/Hide Comments
<?php
$i=0;
while ($i < $num) {
$comment=mysql_result($comments,$i,"comment");
echo "<div id='hidden' style='display:none'><h3>$comment</h3></div>";
$i++;
}
?>
change
$num=mysql_numrows($comments);
to
$num=mysql_num_rows($comments);
the right syntax is mysql_num_rows not mysql_numrows
$i is not set in the first php part:
$variable=mysql_result($comments,$i,"comment");
Fix the above!
There are no records in data base.
$UseComment = "INSERT INTO comments VALUES ('$comment')"; is wrong.
Change it as
$UseComment = "INSERT INTO comments(comment) VALUES ('$comment')";
Thanks.
Firstly, you may check this question.
Regarding with your code, you did not have $i before the line 16 which caused the error:
$variable=mysql_result($comments,$i,"comment");
You should check if there is any result before issuing mysql_result:
$SelectComments = "SELECT * FROM comments";
$comments = mysql_query($SelectComments);
if( $num = mysql_num_rows($comments) ){
$variable = mysql_result($comments, 0, "comment");
}
I would personally write a COUNT query to get the total number of comments:
$sql = 'SELECT COUNT(*) total FROM comments';
$comments = mysql_query($sql);
$row = mysql_fetch_assoc($comments);
$totalComments = $row['total'];
In this case, you don't need to check with mysql_num_rows() because the COUNT query will definitely return one result "0" or whatever.

Categories