postgresql check if exists while executing prepared statement - php

I'm preparing some statements and want to check if the row exists before I update. If it exists then update it, if it doesn't then output a message "No such animal". I have the update bit working, but unsure how to check if the row exists. Please assist.
$v = array();
$v[] = $_POST['status'];
$v[] = $_POST['id'];
$dbh = dbh_get();
$sql = 'UPDATE tap SET status=?
WHERE id =?';
$stmt = $dbh->prepare($sql);
$stmt->execute($v);
\\ if row isn't there display message "No such animal"
\\ otherwise print the below
printf("Status was changed to - %s", $v[0]);
\\then either way have my continue button for me to click on
print '<div class="button" style="float:left;" onclick="window.location.href=\'admin.php\';">Admin</div>' . "\n";
dbh_free($dbh)

According to your question, you want to check if the row exists before performing update. you can try this -
$id_exist = 0;
$sql = "SELECT id
FROM tap" ;
$sql_prepare = $dbh->prepare($sql);
$sql_prepare->execute();
while($row = $sql_prepare->fetchObject()) {
if($_POST['id'] == $row->id) {
$id_exist = 1;
}
}
if($id_exist == 1) {
// perform update here
} else {
echo 'No such animal';
}

Related

PHP doesn't execute functions with sql correct

I will put my code below. I basically check on value in the database and if it's 1 or 0 i want to change it to the opposite (so if 1 change it to 0, if 0 change to 1).
If I execute one SQL statement without using the function (but then it only works one way once) it works. But if I want to execute the specific function with it depending on what the value currently is, it doesn't seem to work. Do you know what I am doing wrong here?
<?php
$date_id = $_POST['dateID'];
$con = mysqli_connect("localhost","root","","secret_name");
$sql = "SELECT * FROM date_list WHERE date_id = ".$dateID;
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
$occupied = $row['occupied'];
if($occupied == 1){
decross_entry();
} elseif( $occupied == 0){
cross_entry();
}else{
echo "Error"
}
}
function decross_entry(){
$dateID = $_POST['dateID'];
$con_2 = mysqli_connect("localhost","root","","secret_name");
$sql_edit = "UPDATE date_list SET occupied= '0' WHERE date_id = ".$dateID;
if($con_2 -> connect_errno){
echo "Failed to connect to database!" . $con_2->connect_error;
}
if ($con_2 -> query($sql_edit) === TRUE)
{
echo "saved!";
} else {
echo "error: " .$sql_edit."<br>".$con_2->error;
}
}
function cross_entry(){
$dateID = $_POST['dateID'];
$con_2 = mysqli_connect("localhost","root","","secret_name");
$sql_edit = "UPDATE date_list SET occupied= '1' WHERE date_id = ".$dateID;
if($con_2 -> connect_errno){
echo "Failed to connect to database!" . $con_2->connect_error;
}
if ($con_2 -> query($sql_edit) === TRUE)
{
echo "saved!";
} else {
echo "error: " .$sql_edit."<br>".$con_2->error;
}
}
?>
If the only possible values of occupied are 0 and 1 then you can do what you want in one query without needing to look up the value of occupied first:
UPDATE date_list
SET occupied = 1 - occupied
WHERE date_id = ?
In PHP, using a prepared query to avoid SQL injection:
$date_id = $_POST['dateID'];
$con = mysqli_connect("localhost","root","","secret_name");
$sql = "UPDATE date_list SET occupied = 1 - occupied WHERE date_id = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param('i', $date_id); // use 's' if $date_id is not an integer
$stmt->execute();

UPDATE RECORDS USING PHP LOOP

I want to update data in my database using php loop.
I have tried updating data, but it only updates the last record in my list and returns all the records as null/zero.
// attempting to update data
$rcount_student_lists = mysqli_query($mysqli, $count_student_lists);
while($row2 = mysqli_fetch_row($rcount_student_lists))
$student_count_count = $row2['0'];
for ($id = 1; $id <=$student_count_count; $id++)
{
$sql = "UPDATE exam_data SET score_s = '".${'dd_'.$id}."' WHERE exam_name_s = '".$one."'";
}
if (mysqli_query($mysqli, $sql)) {
echo juuhead("DETAILS UPDATED SUCCESFULLY");
} else {
echo "Error updating record: " . mysqli_error($mysqli);
}
I would want it to update all the records in the column score_s
You're generating the SQL string in a loop:
for ($id = 1; $id <=$student_count_count; $id++)
{
$sql = ...;
}
But you're only executing it once, because this is outside the loop:
if (mysqli_query($mysqli, $sql)) {
Move the query command inside the loop:
for ($id = 1; $id <=$student_count_count; $id++)
{
$sql = ...
if (mysqli_query($mysqli, $sql)) {
...
} else {
...
}
}
You're also missing braces on your while loop:
while($row2 = mysqli_fetch_row($rcount_student_lists))
$student_count_count = $row2['0'];
Without braces, the while only loops the one line following it. To loop over more than one line, you need to wrap the lines in braces:
while($row2 = mysqli_fetch_row($rcount_student_lists))
{
$student_count_count = $row2['0'];
for ($id = 1; $id <=$student_count_count; $id++)
{
...
}
}
Also, please read about SQL injection. Instead of building queries with string concatenation, use prepared statements with bound parameters. See this page and this post for some good examples.

odbc_num_rows is not work

$stmt is execute and give Result in Print_r($stmt). Result is this "Resource id #4" but when Print_r($stmt) is put in if (odbc_num_rows($stmt) > 0) {Print_r($stmt);}. it's not give Result. and gone else conditon give message else condition.so How to Put odbc function instead of odbc_num_rows($stmt).if right Parameter pass query execute and gone if condition.
which Odbc function used in if condtion.
<?php
include 'Connection.php';
if(isset($_REQUEST["insert"]))
{
$user = $_GET['user'];
$pwd = $_GET['pass'];
$yid = $_GET['yid'];
$sql = "select RegNo, UserName, Pasword from Std_Reg where UserName= '$user' and Pasword = '$pwd' and YearID = $yid and IsActive = True";
$stmt = odbc_exec($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (odbc_num_rows($stmt) > 0)
{
print_r($stmt);
$stmt1 = odbc_fetch_array($stmt);
$product = array();
$product['RegNo'] = $stmt1['RegNo'];
$product['UserName'] = $stmt1['UserName'];
$product['Pasword'] = $stmt1['Pasword'];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
array_push($result["product"], $product);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["succes"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
odbc_close($conn); //Close the connnection first
}
}
?>
For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. The manual says-
Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.
one way around this behaviour is to do a COUNT(*) in SQL instead. See here for an example.

Upload csv and insert or update the results failing

Can anyone see what I am doing wrong here? Basically what is supposed to happen is you upload the csv, it then pulls the rows out and checks with the database if that row exists, if it does it updates it, if it doesn't it inserts it. If the row is blank it ignores it.
What is actually happening is when I upload a csv I just get 'updated' for each of the 4 test lines whether it is in the database or not.
Also if anyone can suggest a better way of doing this, or trimming down the code please let me know, as I know by coding isn't the greatest by any stretch of the imagination.
if(isset($_GET['uploadfile'])) {
$file = fopen($_FILES['csvfile']['tmp_name'], 'r+');
while(! feof($file))
{
$line = fgetcsv($file, 0, ',');
list($productcode, $v9cm, $v1litre, $v2litre, $v3litre, $v5litre, $v7litre) = $line;
$rowcheck = "SELECT * FROM `stock` WHERE `productcode` = '$productcode'";
if (#mysql_num_rows(mysql_query($rowcheck))!=1) {
if ($productcode == NULL OR $productcode == ''){}
else {
$datecreated = date('Y-m-d');
// Insert Posted Data
mysqli_query($db,"INSERT INTO stock (`datecreated`, `productcode`, `9cm`, `1litre`, `2litre`, `3litre`, `5litre`, `7litre`) VALUES ('$datecreated', '$productcode', '$v9cm', '$v1litre', '$v2litre', '$v3litre', '$v5litre', '$v7litre')") or die ('Unable to execute query. '. mysqli_error());
echo $productcode.' - Added<br/ >';
}
}
else{
if ($productcode == NULL OR $productcode == ''){}
else {
$stmt = $db->prepare("UPDATE stock SET 9cm = '$v9cm',1litre = '$v1litre',2litre = '$v2litre',3litre = '$v3litre',5litre = '$v5litre',7litre = '$v7litre' WHERE productcode = '$productcode'");
if ($stmt === FALSE) { echo "an error has occured"; }
$stmt->execute();
$stmt->close();
echo $productcode.' - Updated<br/ >';
}
}
}
fclose($file);
}
}
There seemed to be a brace missing which I think would indeed have made it try to update whatever - indented statements to help make it a bit clearer and added mysqli instead of mysql where it appeared to be wrong - assuming everything should be mysqli. Hope that may help.
You will need to add clean-up/sanitizing/escape code but I assume you know that
if(isset($_GET['uploadfile'])){
$file = fopen($_FILES['csvfile']['tmp_name'], 'r+');
while(! feof($file)){
$line = fgetcsv($file, 0, ',');
list($productcode, $v9cm, $v1litre, $v2litre, $v3litre, $v5litre, $v7litre) = $line;
$rowcheck = "SELECT * FROM `stock` WHERE `productcode` = '$productcode'";
if (#mysqli_num_rows(mysqli_query($rowcheck))!=1){
if ($productcode == NULL OR $productcode == ''){
echo "Product code missing and rowcheck is not 1<br/ >"; // for testing
}else{
$datecreated = date('Y-m-d');
// Insert Posted Data
mysqli_query($db,"INSERT INTO stock (`datecreated`, `productcode`, `9cm`, `1litre`, `2litre`, `3litre`, `5litre`, `7litre`) VALUES ('$datecreated', '$productcode', '$v9cm', '$v1litre', '$v2litre', '$v3litre', '$v5litre', '$v7litre')") or die ('Unable to execute query. '. mysqli_error());
echo $productcode.' - Added<br/ >';
}
}elseif($productcode == NULL OR $productcode == ''){
echo "Product code missing<br/ >"; // for testing
}else{
$stmt = $db->prepare("UPDATE stock SET 9cm = '$v9cm',1litre = '$v1litre',2litre = '$v2litre',3litre = '$v3litre',5litre = '$v5litre',7litre = '$v7litre' WHERE productcode = '$productcode'");
if ($stmt === FALSE){
echo "an error has occured<br/ >";
}else{
$stmt->execute();
$stmt->close();
echo $productcode.' - Updated<br/ >';
}
}
}
}
You might also like to look at the security implications of using uploaded files directly by their temp name http://www.acunetix.com/websitesecurity/php-security-4/ among many others.
This is what worked in the end :
if(isset($_GET['uploadfile'])){
$file = fopen($_FILES['csvfile']['tmp_name'], 'r+');
while(! feof($file)){
$line = fgetcsv($file, 0, ',');
list($productcode, $v9cm, $v1litre, $v2litre, $v3litre, $v5litre, $v7litre) = $line;
$query = mysqli_query($db, "SELECT * FROM stock WHERE productcode='".$productcode."'");
if(mysqli_num_rows($query) > 0){
$stmt = $db->prepare("UPDATE stock SET 9cm = '$v9cm',1litre = '$v1litre',2litre = '$v2litre',3litre = '$v3litre',5litre = '$v5litre',7litre = '$v7litre'
WHERE productcode = '$productcode'");
if ($stmt === FALSE) { echo "an error has occured"; }
$stmt->execute();
$stmt->close();
echo $productcode.' - Updated<br/ >';
}else{
// do something
if (!mysqli_query($db,$query))
{
$datecreated = date('Y-m-d');
// Insert Posted Data
mysqli_query($db,"INSERT INTO stock (`image`,`genusid`,`datecreated`, `productcode`, `9cm`, `1litre`, `2litre`, `3litre`, `5litre`, `7litre`) VALUES ('None.gif','5','$datecreated', '$productcode', '$v9cm', '$v1litre', '$v2litre', '$v3litre', '$v5litre', '$v7litre')") or die ('Unable to execute query. '. mysqli_error());
echo $productcode.' - Added<br/ >';
}
}
}}}
It may be easier to use mysql's ON DUPLICATE KEY UPDATE clause (http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html).
See hjpotter92's answer here: On Duplicate Key Update same as insert. Your query would need to be modified to something like this:
INSERT INTO table (id,a,b,c,d,e,f,g)
VALUES (1,2,3,4,5,6,7,8)
ON DUPLICATE KEY
UPDATE a=a, b=b, c=c, d=d, e=e, f=f, g=g;
This should allow you to remove most of the conditional logic and also cut down on the number of queries you run.

Update tinyint(1)

I would like to update the status value -tinyint(1)- to activate and deactivate the user. Whenever I try to update I keep getting the message below which set to "Attendant update failed." Any help is appreciate it. Thanks
if (empty($errors)) {
// Perform Update
$id = $attendant["id"];
$status = mysql_prep($_POST["status"]);
$query = "UPDATE attendant SET ";
$query .= "status = '{$status}', ";
$query .= "WHERE id = {$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
// Success
$_SESSION["message"] = "Attendant updated.";
redirect_to("activate_attendant.php");
} else {
// Failure
$_SESSION["message"] = "Attendant update failed.";
}
}
} else {
// This is probably a GET request
}
Remove the trailing comma in status = '{$status}', <=
MySQL would have thrown you an error by doing:
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
I would also like to note that your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they're much safer.

Categories