PHP SQL UPDATE if Exist or INSERT if not? - php

I need to update if there is any field with the same model_name and only update the led_data and status
public function NewModelsBin($data)
{
$qry = "INSERT INTO LABELS_LEDS (PROJECT, MODEL_NAME, NO_LED,LED_PN,LED_DATA,STATUS) VALUES ('".$data['proyecto']."', '".$data['model_name']."', '".$data['no_led']."','
".$data['led_pn']."','".$data['led_data']."','".$data['status']."') ";
//"INSERT ON DUPLICATE KEY UPDATE LED_DATA (LED_DATA, STATUS) VALUES ('".$data['led_data']."', '".$data['status']."')";
echo $qry;
$stmt = sqlsrv_query( $this->conn,$qry);
if( $stmt === false) {
die( print_r( sqlsrv_errors() . " fallo la query " . $qry , true) );
}
sqlsrv_free_stmt( $stmt);
}

for this first, you will need to first run a select query to find in database entry with the model name after then add if condition. to add new entry id doesn't exist and update if exist.

public function NewModelsBin($data)
{
$qry="SELECT * FROM LABELS_LEDS WHERE MODEL_NAME='".$data['model_name']."'";
$stmt = sqlsrv_query( $this->conn,$qry);
if(sqlsrv_has_rows($stmt)){
//UPDATE QUERY HERE
}
else{
$qry = "INSERT INTO LABELS_LEDS (PROJECT, MODEL_NAME,
NO_LED,LED_PN,LED_DATA,STATUS) VALUES ('".$data['proyecto']."',
'".$data['model_name']."', '".$data['no_led']."','
".$data['led_pn']."','".$data['led_data']."','".$data['status']."') ";
echo $qry;
$stmt = sqlsrv_query( $this->conn,$qry);
if( $stmt === false) {
die( print_r( sqlsrv_errors() . " fallo la query " . $qry , true) );
}
sqlsrv_free_stmt( $stmt);
}
}
Here's my solution..

Related

Query doesn't insert value into DB

In my query the update statement doesn't work, the error given is:
Number of parameter doesn't match with prepared statement
this is my code:
public function update_resource($resource)
{
$mysqli = new MySQLi(HOST, USERNAME, PASSWORD, DATABASE);
$this->connection_state($mysqli);
$id = $resource['id'];
$descrizione = $resource['descrizione'];
$sigla = $resource['sigla'];
$colore = $resource['colore'];
$planning = $resource['planning'];
try
{
$query = "UPDATE risorse SET descrizione = '$descrizione'
AND sigla = '$sigla' AND colore = '$colore' AND planning = '$planning'
WHERE id = '$id' ";
$stmt = $mysqli->prepare($query);
$stmt -> bind_param("ssssi", $descrizione, $sigla, $colore, $planning, $id);
echo $query;
if($stmt->execute())
{
echo "Added!";
}
else
{
echo "Err: " . $stmt->error;
}
}catch(Exception $e){ echo $e->getMessage(); }
}
The code go into the Added condition but the query fail, what's the problem?
public function update_resource($resource)
{
$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $resource['id'];
$descrizione = $resource['descrizione'];
$sigla = $resource['sigla'];
$colore = $resource['colore'];
$planning = $resource['planning'];
try
{
$query = "UPDATE risorse SET descrizione = '$descrizione'
, sigla = '$sigla', colore = '$colore', planning = '$planning'
WHERE id = '$id' ";
$stmt = $mysqli->prepare($query);
$stmt -> bind_param($descrizione, $sigla, $colore, $planning, $id);
echo $query;
if($stmt->execute())
{
echo "Added!";
}
else
{
echo "Err: " . $stmt->error;
}
}catch(Exception $e){ echo $e->getMessage(); }
}?
Your problem is that you don't have any placeholders in your query.
Refer to manual to see how placeholders should be set.
In general, placeholders are ? which later will be replaced with values, so your query should look like:
$query = "UPDATE risorse SET descrizione = ?
AND sigla = ? AND colore = ? AND planning = ?
WHERE id = ?";
please visit on http://php.net/manual/en/pdostatement.bindparam.php.you got your answer.see Example #1 Execute a prepared statement with named placeholders

Insert values with if condition with mysqli

I am trying to make register member page. If a new member insert an email which has been already exist, then there will be a notification saying that the email is exist. But if the email has not been exist, the values they insert in the form will be send to database.
I don't know what is wrong with my code bellow. It just blank and doesn't send anything to databse. I need a help.
<?php
//conection:
$link = mysqli_connect(".com","klaudia","intheclaud","elektro") or die("Error " . mysqli_error($link));
//consultation:
$member_id=$_GET['member_id'];
$member_name=ucwords(htmlspecialchars($_POST['member_name']));
$member_email=$_POST['member_email'];
$member_password=htmlspecialchars($_POST['member_password']);
$member_phone=$_POST['member_phone'];
$member_address_satu=ucwords(htmlspecialchars($_POST['member_address_satu']));
$member_address_dua=ucwords(htmlspecialchars($_POST['member_address_dua']));
$member_reference=$_POST['member_reference'];
$query = "SELECT * FROM member_registry WHERE member_email='$member_email '" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
if (mysqli_num_rows($result) > 0) {
echo "This email you are using has been registered before";
}
else {
mysqli_query($link, "INSERT INTO member_registry (
'member_id',
'member_name',
'member_email',
'member_password',
'member_phone',
'member_address_satu',
'member_address_dua',
'member_reference')
VALUES (0,1,2,3,4,5,6,7,8)";
?>
I have tried to check the connection and the database. Everything works fine here. When I insert someone name which has been in the table of the database, it will echo that the email already exist. and vice versa.
$query = "SELECT * FROM member_registry WHERE member_name='Klaudia '" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
if (mysqli_num_rows($result) > 0) {
echo "This email you are using has been registered before";
}
else {
echo "This email you are using has NOT been registered before";
}
[UPDATE]
mysqli_query($link, "INSERT INTO member_registry (
'member_id',
'member_name',
'member_email',
'member_password',
'member_phone',
'member_address_satu',
'member_address_dua',
'member_reference')
VALUES (0,1,2,3,4,5,6,7,8)");
}
?>
You shouldn't handle this by two separate queries (at least without a transaction).
Instead create a unique index that doesn't allow the same email address twice in the table and check for the specific ER_DUP_ENTRY error code to detect doublets.
sscce:
<?php
define('MYSQL_ER_DUP_ENTRY', 1062);
$mysqli = new mysqli('localhost', 'localonly', 'localonly', 'test');
if ($mysqli->connect_errno) {
trigger_error('connection failed', E_USER_ERROR);
}
$result = $mysqli->query('
CREATE TEMPORARY TABLE soFoo (
id int auto_increment,
email varchar(128),
primary key(id),
unique key(email)
)'
);
if ( !$result) {
trigger_error('create table failed', E_USER_ERROR);
}
$stmt = $mysqli->prepare('INSERT INTO soFoo (email) VALUES (?)');
if (!$stmt) {
trigger_error('prepare failed', E_USER_ERROR);
}
$result = $stmt->bind_param("s", $email);
if ( !$result) {
trigger_error('bind_param failed', E_USER_ERROR);
}
foreach( array('email1', 'email2', 'email1') as $n=>$email ) {
echo $n, ' ', $email;
$result = $stmt->execute();
if ( $result ) {
echo " ok\r\n";
}
else {
if ( MYSQL_ER_DUP_ENTRY==$stmt->errno ) { // <-- here's the test for the duplicate entry
echo " duplicate\r\n";
}
else {
var_dump($stmt->errno, $stmt->error);
}
}
}
prints
0 email1 ok
1 email2 ok
2 email1 duplicate
You have an error in your syntax. You don't close your function.
Also you shouldn't use single quotes around your coumn names.
mysqli_query($link, "INSERT INTO member_registry (
`member_id`,
`member_name`,
`member_email`,
`member_password`,
`member_phone`,
`member_address_satu`,
`member_address_dua`,
`member_reference`)
VALUES (0,1,2,3,4,5,6,7,8)");

Using Session variable as WHERE predicate; am I approaching it wrongly?

We would like to query our database and sample records based on a particular user's department.
Given the app design, the only way I know to do this is to filter the query by using dept's session variable.
The code below is not working.
Data gets returned if I comment out the session variable.
Nothing is getting retrieved with the session variable as filter.
Any ideas what I am doing wrong?
Is the session variable route the wrong approach?
Thanks in advance for help.
//Start your session
session_start();
// Connect to SQL Server database
include("../sqlConnect.php");
// Construct query
$loginName = $_GET['loginName'];
//Ok, let's grab user's dept from query
$sql = "SELECT ISNULL(dept,'NA') AS 'dept' FROM emp where ([userName]) = lower('$userName')"
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false )
{
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
$results = array();
while($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) {
array_push($results,$row);
$dept = $row['dept'];
}
//Store department in the session
$_SESSION['dept'] = $dept;
//Now extract records based on dept
$tsql ="SELECT
r.REQUESTID,
convert(char(10),r.[currDate],101),
r.[startedDBY],
e.[dept],
e.[WORKPHONE],
e.[EMAIL],
r.[DESCRIPTION],
r.[DETAILS],
r.[PROBLOCATION],
c.[COMMENTS]'
FROM EMPLOYEE e,REQUEST r,CUSTOMERCALL c
WHERE LOGINNAME='$loginName'
AND c.REQUESTID=r.requestid
AND e.dept = '" . $_SESSION['dept'] . "'
";
$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false )
{
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
$results = array();
while($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) {
array_push($results,$row);
}
echo json_encode($results);
// Free connection resources
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);

data Not Storing

this is my connection class
class Connection {
public function query($sql){
mysql_connect('localhost','root','') or die("Connection error ". mysql_error());
mysql_select_db('liontours') or die("Database error ". mysql_error());
$results = mysql_query($sql);
$last_inserted_id = mysql_insert_id();
return array('results'=>$results, 'last_id'=>$last_inserted_id);
}
}
this is my model
public function V_reg($v_no, $dl_no, $owner, $o_name, $o_nic, $i_date, $ex_date, $p_report, $nic, $s_name, $f_name, $initials, $dob, $stat, $v_type) {
$sql = "INSERT INTO `vehicledetails`(`vehicle_no`, `owner`, `owner_name`, `owner_nic`, `insured_date`, `ex_date`, `police_report`,`type`)
VALUES ('$v_no','$owner','$o_name','$o_nic','$i_date','$ex_date','$p_report','$v_type')";
$conn = new Connection();
//vehicle id of last inserted record
$vehicle_id = mysql_insert_id();
$results = $conn->query($sql);
$last_vehicle_record_id = $results['last_id'];
$fk_key = $last_vehicle_record_id;
//checking the first table insert successful if so do the second insert else must define counter measure in else part
if ($fk_key !== 0) {
$sql1 = "INSERT INTO driverdetails (id, vehicle_id, nic,sir_name,first_name,dlNo,initials,dob,status )
VALUES ('null', '$fk_key', '$nic','$s_name','$f_name','$dl_no', '$initials','$dob','$stat')";
$results = $conn->query($sql1);
}else{
die('transaction failed').mysql_error();
}
return $results;
}
}
i don't know what is wrong with this coding but it's not passing the data all the time it says transaction failed and no error given. just the text can some body tell me any thing wrong with this coding ? if there is no coding errors is it a problem with my database ?

Grabbing last insert id sqlsrv

I am working on a php code where I insert into two tables and want to grab the id from the first table I inserted into, right now I am getting this error: Call to undefined function sqlsrv_field(). I am trying to grab the routine_id from the table routines.
Code:
date_default_timezone_set('Europe/Oslo');
$date = strftime ('%Y-%m-%d');
$time = strftime('%H:%M:%S');
$value = $_GET['Temp'];
$conn = sqlsrv_connect('BILAL' , $conn_array);
$sql = "Insert into routines (date, time, value, emp_id) values ('$date', '$time', '$value', (SELECT id FROM emps WHERE user_name='Arduino'))";
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
$query = sqlsrv_query( $conn, $sql);
if( $query === false ) {
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_next_result($query);
sqlsrv_fetch($query);
$id = sqlsrv_field($query,0);
$sql2 = "Insert into measure_routines (routine_id, measure_id, pool_id) values ('$id', (Select id from measurements where title='A_Auto_Temperatur'), 1 )";
$stmt = sqlsrv_query( $conn, $sql2);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
There is no function called sqlsrv_field(). Instead, use sqlsrv_get_field():
...
sqlsrv_next_result($query);
bool fetchStatus = sqlsrv_fetch($query);
if(fetchStatus === false) {
die( print_r( sqlsrv_errors(), true));
}
if(fetchStatus === null) {
// Some work when there are no results in the result set
} else {
$id = sqlsrv_get_field($query, 0);
}
...
This should solve your problem basically. However your code is vulnerable to SQL injection. Instead of giving values directly into the sql query, consider using prepared statements.
There are many articles about that, here is one I found in quick search:
What's the Right Way to Prevent SQL Injection in PHP Scripts?
Try this:
function lastId($queryID) {
sqlsrv_next_result($queryID);
sqlsrv_fetch($queryID);
return sqlsrv_get_field($queryID, 0);
}
$lastInsertedId = lastId($stmt);

Categories