I'm trying to insert data to my SQL Server database from PHP. I don't get any error, but data is not applied to db. I was trying with the same query but reformed to normal database query and it worked so I assume there is something wrong with my code:
$query1 = "
INSERT INTO KPI(KPI_new_name, KPI_definition, KPI_tech_name)
VALUES('$KPI_new_name','$KPI_definition','$KPI_tech_name')
";
$query2 = "
INSERT INTO ReportsKpiRel(Report_Id, KPI_Id)
select r.Report_Id, kpis.KPI_Id
from Reports r
inner join ReportsKpiRel RKR on r.Report_Id = RKR.Report_Id
inner join KPI kpis on RKR.KPI_Id = kpis.KPI_Id
where r.Report_Id = '".$repid."' and kpis.KPI_new_name = '".$KPI_new_name."'
";
$qresult = sqlsrv_query($conn, $query1);
if ($qresult)
{
$qresult2 = sqlsrv_query($conn, $query2);
if($qresult2)
{
echo "Success!";
}
else
echo "Failed!";
}
else
echo "error!";
First query goes smoothly. Second is not working. Have you got any idea what is wrong?
Original answer:
You need to check for errors after each sqlsrv_query() call. But, the more important issue with your approach, is that your code is open to possible SQL injection attacks. Always try to use parameterized queries. As is mentioned in the documentation, the sqlsrv_query function is well-suited for one-time queries and should be the default choice to execute queries unless special circumstances apply and sqlsrv_query function does both statement preparation and statement execution, and can be used to execute parameterized queries.
The following code, based on the code in the question, is a possible solution to your problem:
<?php
$query1 = "
INSERT INTO KPI(KPI_new_name, KPI_definition, KPI_tech_name)
VALUES(?, ?, ?)
";
$query2 = "
INSERT INTO ReportsKpiRel(Report_Id, KPI_Id)
select r.Report_Id, kpis.KPI_Id
from Reports r
inner join ReportsKpiRel RKR on r.Report_Id = RKR.Report_Id
inner join KPI kpis on RKR.KPI_Id = kpis.KPI_Id
where r.Report_Id = ? and kpis.KPI_new_name = ?
";
$params1 = array($KPI_new_name, $KPI_definition, $KPI_tech_name);
$result1 = sqlsrv_query($conn, $query1, $params1);
if ($result1 === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
$params2 = array($repid, $KPI_new_name);
$result2 = sqlsrv_query($conn, $query2, $params2);
if ($result2 === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
echo "Success!";
?>
Update:
It seems that you have a different problem. So, if you want to handle many-to-many relationship and the KPI table has an identity column, you need to get the generated value using SCOPE_IDENTITY():
<?php
// INSERT into KPI
$query1 = "
SET NOCOUNT ON;
INSERT INTO KPI(KPI_new_name, KPI_definition, KPI_tech_name)
VALUES(?, ?, ?);
SELECT SCOPE_IDENTITY() AS KPI_Id
";
$params1 = array($KPI_new_name, $KPI_definition, $KPI_tech_name);
$result1 = sqlsrv_query($conn, $query1, $params1);
if ($result1 === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
$row = sqlsrv_fetch_array($result1, SQLSRV_FETCH_ASSOC);
$kpiid = $row['KPI_Id'];
// INSERT into ReportsKpiRel
$query2 = "
INSERT INTO ReportsKpiRel(Report_Id, KPI_Id)
VALUES (?, ?)
";
$params2 = array($repid, $kpiid);
$result2 = sqlsrv_query($conn, $query2, $params2);
if ($result2 === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
?>
Related
I have an auto incrementing ID called deviceID in one of my fields. I was wanting to pass this to a session in php to use later on and was planning on using scope_identity() as I understand that this is the best way to get the current Primary key ID. However anytime I have attempted to use it I have had a error message saying that it is an undefined function. Here is my code so without the scope_identity():
<?php
session_start();
include 'db.php';
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
$_SESSION["screenWidth"] = $screenWidth;
$_SESSION["screenHeight"] = $screenHeight;
if (isset($_POST['submit'])) {
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$phoneType = $_POST['phoneName'];
$HandUsed = $_POST['HandUsed'];
$_SESSION["HandUsed"] = $HandUsed;
$_SESSION["phoneName"] = $phoneType;
echo 'hello';
$sql = "
INSERT INTO DeviceInfo (DeviceID, screenWidth, phoneType, screenHeight, HandUsed)
VALUES ('$screenWidth','$phoneType', '$screenHeight', '$HandUsed')
SELECT SCOPE_IDENTITY() as DeviceID
";
if (sqlsrv_query($conn, $sql)) {
echo ($sql);
echo "New record has been added successfully !";
} else {
echo "Error: " . $sql . ":-" . sqlsrv_errors($conn);
}
sqlsrv_close($conn);
}
?>
You need to fix some issues in your code:
The INSERT statement is wrong - you have five columns, but only four values in this statement. I assume, that DeviceID is an identity column, so remove this column from the column list.
Use parameteres in your statement. Function sqlsrv_query() does both statement preparation and statement execution, and can be used to execute parameterized queries.
Use SET NOCOUNT ON as first line in your statement to prevent SQL Server from passing the count of rows affected as part of the result set.
SCOPE_IDENTITY() is used correctly and it should return the expected ID. Of course, depending on the requirements, you may use IDENT_CURRENT().
The following example (based on the code in the question) is a working solution:
<?php
session_start();
include 'db.php';
if (isset($_POST['submit'])) {
$screenWidth = $_POST['screenWidth'];
$phoneType = $_POST['phoneName'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
$params = array($screenWidth, $phoneType, $screenHeight, $HandUsed);
$sql = "
SET NOCOUNT ON
INSERT INTO DeviceInfo (screenWidth, phoneType, screenHeight, HandUsed)
VALUES (?, ?, ?, ?)
SELECT SCOPE_IDENTITY() AS DeviceID
";
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
echo "Error: " . $sql . ": " . print_r(sqlsrv_errors());
exit;
}
echo "New record has been added successfully !";
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo $row["DeviceID"];
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
}
?>
I've seen a few posts dealing with UPDATE statements in MySQL, but none of them seem to apply to my specific situation.
I have the following code:
$result = "SELECT iso_date FROM open_lab_report WHERE iso_date = current_timestamp";
if(!mysqli_query($link, $result)) {
$sql = "INSERT INTO open_lab_report (iso_date, lab_monitor, incidentReport) VALUES (current_timestamp, '$lab_monitor', 1)";
}else{
$sql = "UPDATE open_lab_report SET incidentReport = 1 WHERE iso_date = current_timestamp";
}
if(!mysqli_query($link, $sql)) {
echo "Query failed, code: " . mysqli_errno($link);
}
Essentially, I'm trying to check to see if an entry exists. If it exists, then update it. If the entry doesn't exist, then make it.
The INSERT statement executes perfectly. However, the UPDATE statement does nothing. There is no error message, and no changes made in my table.
Any ideas?
Thanks!
As Forbs stated, your UPDATE statement will not result in any changes since you are filtering based on "current_timestamp", which will be whatever time the query executes. What you need to do instead is pass an existing timestamp into your code so that it updates whatever existing record already has that as its iso_date.
See the example below for how you can change your code.
//this is whatever your time is that you are looking for a record for
$isoDateDT = '2018-08-01 08:15:00';//human readable datetime
$isoDateTS = strtotime($isoDateDT);//unix timestamp
$result = "SELECT * FROM open_lab_report WHERE iso_date = $isoDateTS";
if(!mysqli_query($link, $result)) {
$sql = "INSERT INTO open_lab_report (iso_date, lab_monitor, incidentReport) VALUES ($isoDateTS, '$lab_monitor', 1)";
} else {
$sql = "UPDATE open_lab_report SET incidentReport = 1 WHERE iso_date = $isoDateTS";
}
if(!mysqli_query($link, $sql)) {
echo "Query failed, code: " . mysqli_errno($link);
}
You have to correct your if statement checking.
In your Case you can count number of entries with same timestamp as current timestamp.
and then
if count<1 then you can UPDATE ,otherwise INSERT.
EXAMPLE:
$result = "SELECT iso_date FROM open_lab_report WHERE iso_date = current_timestamp";
$row=mysqli_num_rows(mysqli_query($link, $result))
if($row<1){
$sql = "INSERT INTO open_lab_report (iso_date, lab_monitor, incidentReport) VALUES (current_timestamp, '$lab_monitor', 1)";
}else{
$sql = "UPDATE open_lab_report SET incidentReport = 1 WHERE iso_date = current_timestamp";
}
if(!mysqli_query($link, $sql)) {
echo "Query failed, code: " . mysqli_errno($link);
}
I want to GET user id FROM players WHERE username='$username' and post it into another MySQLi query and post it as pid but it shows error somehow, did I miss something?
if(isset($_POST["add"])) {
$content = $_POST['content'];
$sql = "SELECT id FROM players WHERE username='$username'";
$sql1 = "INSERT INTO bulletinboard (pid,content) VALUES ('$sql','$content')";
if (mysqli_query($conn, $sql1)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
This is the error I am receiving.
Error: SELECT id FROM players WHERE username='nasty93'
Thanks
You need to execute the query so it needs to not be quoted. You also should familiarize yourself with the insert...select syntax. http://dev.mysql.com/doc/refman/5.7/en/insert-select.html
You also should use parameterized queries. Here it is altered (untested) (I also only use mysqli on SO so likely to be an error here).
if(isset($_POST["add"])) {
$content = $_POST['content'];
$sql1 = "INSERT INTO bulletinboard (pid,content) SELECT id, ? FROM players WHERE username=?";
$stmt = mysqli_prepare($conn, $sql1) or die(mysqli_error($conn));
mysqli_stmt_bind_param($stmt, "ss", $content, $username) or die(mysqli_error($conn));
mysqli_stmt_execute($stmt) or die(mysqli_error($conn));
}
I'm new to PDO, I'm using it as advised by senior users in this website.
I'm trying to get data from my table using pdo, using while, so I can get all the data "organized".
My query is working, but for some reason I can't even dump it.
Heres my code:
$sql = $conn->query("SELECT id, nivel, tipo, titulo, texto, ativa FROM account.quests_faq WHERE ativa='YES' ORDER BY nivel DESC");
while($row = $conn->fetch(PDO::FETCH_ASSOC)){
if ($tipo=='main'){
echo '<li><font color="green">Nivel '$row['nivel']' - '$row['titulo']'</font></li><br>';
}else{
echo '<li><font color="red">Nivel '$row['nivel']' - '$row['titulo']'</font></li><br>';
}
}
So, in a resume.
I have a table with titles, some text and an id.
I want to get this data from it and echo it.
Hope you can help me, sorry for the newb doubt.
EDIT 1:
$username = 'sssss';
$password = 'sssss';
$conn = new PDO('mysql:host=xxxxxxxx;dbname=account', $username, $password);
$sql = "SELECT id, nivel, tipo, titulo, texto, ativa FROM account.quests_faq WHERE ativa='YES' ORDER BY nivel DESC";
$stmt = $conn->query($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo '<li><font color="green">Nivel '.$row['nivel'].' - '.$row['titulo'].'</font></li><br>';
}else{
echo '<li><font color="red">Nivel '.$row['nivel'].' - '.$row['titulo'].'</font></li><br>';
}
}
Well, advise you were given is wrong.
Not use but learn.
You have to learn something before using it.
There are many tutorials on PDO around (all of them crappy ones though) but at least you can learn proper syntax from there
$sql = "SELECT id, nivel, tipo, titulo, texto, ativa FROM account.quests_faq WHERE ativa='YES' ORDER BY nivel DESC";
// look this string contains SQL query. so, the variable is named $sql
$stmt = $conn->query($sql);
// in the next line we are getting a statement object from the function query()
// this is why variable called $stmt
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// and now we can start iterating this statement.
// statement, Carl. Not connection to database
// which is called $conn, if you get an idea
also you have to enable error reporting for PDO.
And yes, as it was said in the other answer, your PHP syntax is also wrong. You are supposed to learn it too, instead of banging together random lines of code and then asking others to fix it for you.
Start from less complex syntax, from echoing one single variable without decoration. And ask one question per post. As for the PDO part you already got the answer
Try using a foreach loop. Once the loop is finished you can actually use the $arrRows array anywhere throughout the file! I was told by one of the senior web developers that this is a better way to do it.
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $key => $arrRows){
echo $arrRows['COLLUMN_NAME_HERE'];
}
Here is a demo function that will select values from a table using PDO
function showPost($uID){
global $numRecords, $dbConnection, $stmt;
connect(); //Run connect function (../connections/connections.php)
$sqlStr = "SELECT user_post.*, user.name, user.avatar FROM user_post JOIN user ON user_post.uID = user.uID WHERE user_post.uID = ".$uID. " ORDER BY post_time DESC";
//Run Query
try
{
$stmt = $dbConnection->query($sqlStr);
if($stmt === false)
{
die("Error executing the query: $sqlStr");
}
}
catch(PDOException $error)
{
//Display error message if applicable
echo "An error occured: ".$error->getMessage();
}
$numRecords = $stmt->rowcount();
//Close the databaase connection
$dbConnection = NULL;
}
Let me know if you have anymore questions
You were using your connection variable conn instead of your query variable sql to fetch your query results.
$sql = $conn->query("SELECT id, nivel, tipo, titulo, texto, ativa FROM account.quests_faq WHERE ativa='YES' ORDER BY nivel DESC");
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
if ($tipo=='main')
echo '<li><font color="green">Nivel '$row['nivel']' - '$row['titulo']'</font></li><br>';
else
echo '<li><font color="red">Nivel '$row['nivel']' - '$row['titulo']'</font></li><br>';
}
Or you can do similarly using Prepared Statements
$sql = $conn->prepare("SELECT id, nivel, tipo, titulo, texto, ativa FROM account.quests_faq WHERE ativa='YES' ORDER BY nivel DESC");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
if ($tipo=='main')
echo '<li><font color="green">Nivel '$row['nivel']' - '$row['titulo']'</font></li><br>';
else
echo '<li><font color="red">Nivel '$row['nivel']' - '$row['titulo']'</font></li><br>';
}
I have the following two queries. Second query is dependent on first one.
$query1 = mysql_query("Insert into table_one set ---- ");
if($query1)
{
$query2 = mysql_query("delete from table_two where condition---");
if($query2)
{
$message = "both queries executed successfully";
}
else
{
$del = mysql_query("delete record inserted by $query1");
}
}
Can we execute these two queries in a single statement so that both queries depend on each other.If INSERT query fail, DELETE query also fail it's execution as well as if DELETE query fail INSERTION in query first fail.
Thanks
If I good understand what you need, simply use transactions.
Run this query before your insertion:
mysql_query('begin');
And then, if everything went fine, commit the transaction:
mysql_query('commit');
In case of any failures, you may rollback every change you made:
mysql_query('rollback');
Note that in case of MySQL, the MyISAM engine does not support rollback in transactions, so use InnoDB.
Read more about transactions here: https://dev.mysql.com/doc/refman/5.0/en/commit.html
Example with your code:
<?PHP
mysql_query('begin'); //start transaction
$query1 = mysql_query("Insert into table_one set ---- ");
if($query1)
{
$query2 = mysql_query("delete from table_two where condition---");
if($query2)
{
mysql_query('commit'); //both queries went fine, so let's save your changes and end the transaction
$message = "both queries executed successfully";
}
else
{
mysql_query('rollback'); //query2 failed, so let's rollback changes made by query1 and end the transaction
}
}
else
mysql_query('rollback'); //query1 failed, so let's end the transaction
If query2 fails it doesn't check query1.
$query1 = mysql_query("Insert into table_one set ---- ");
$query2 = mysql_query("delete from table_two where condition---");
if( $query2 && $query1)
{
$message = "both queries executed successfully";
}
else if(!$query2)
{
$del = mysql_query("delete record inserted by $query1");
}
You can use transaction, if any query fails then call rollback, otherwise commit
I found a best solution.
Extending idea of #Luki i wrote the following code and it give me too much satisfied answer. First use the following function.
function multi_statement()
{
global $conn;
$total_args = func_get_args();
$args = implode($total_args,";");
$args = "begin;".$args.";commit;";
$number = 0;
if($conn->multi_query($args))
{
do
{
if ($conn->more_results())
{
$number++;
}
}
while($conn->next_result());
}
if($number < (count($total_args)+1))
{
$conn->query('rollback');
echo "Sorry..!!! Error found in Query no:".$number;
}
else
{
echo "All queries executed successfully";
}
}
Then I called the function with number of statements, all these statements are dependent on each other. In-case there is error in any query, no one query occur any changes in database.
$statement1 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as1', 'as1')";
$statement2 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as2', 'as2')";
$statement3 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as3', 'as3')";
$statement4 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as4', 'as4')";
$statement5 = "DELETE from user where user_id = '12'";
multi_statement($statement1,$statement2,$statement3,$statement4,$statement5);