checking if column is zero before updating - php

How do i insert into a database checking if the column is zero before inserting into it
this is what i have tried but after updating it still insert a new row with the last inserted ID but rather i just want it to update without inserting
$lastID = mysqli_insert_id($DBcon);
$query2=$DBcon->query("SELECT * FROM mergeing");
$compare_value = "0";
if($row = $query2->fetch_array()) {
$merger = "INSERT into mergeing(donator_1) VALUES ('$lastID')";
if($row['donator_2'] !== "$compare_value") {
if ($DBcon->query($merger)) {
echo "success second";
}
}
}
while ($row = $query2->fetch_array()) {
$idd= $row["_id"];
$merg2 = "UPDATE mergeing SET donator_2='".$lastID."' WHERE _id=$idd";
if($row['donator_2'] === "$compare_value") {
if ($DBcon->query($merg2)) {
echo "success";
}
}
}

It seems you want to check if there is a record that has a specific donator_2 value, and if so, you want it updated. If no such value is present, you want to insert a new record.
Then your code could look like this:
$lastID = mysqli_insert_id($DBcon);
$compare_value = 0;
$DBcon->query("UPDATE mergeing SET donator_2 = $lastID WHERE donator_2 = $compare_value");
if ($DBcon->affected_rows) {
echo "success: updated";
} else {
$DBcon->query("INSERT into mergeing(donator_1) VALUES ($lastID)");
echo "success: inserted";
}
Depending on your actual use case, but you might want to also set the donator_2 value when you insert the new record.
Please note that if the $compare_value is determined by user input or some other source that you cannot predict, then you should use prepared statements, as otherwise the code is open to SQL injection.

Related

How to use SUBSTRING and use it on making a data unique in PHP

I am trying to do this in my PHP code, the thing is I haven't figured it out yet. I want to make the first 3 characters UNIQUE but still the data is saved. For example if I input GTX-1070 and will Input another entry named GTX-3080 it should not be saved because "GTX" was already been used. I am doing this without using unique constraint in SQL.
Here is my PHP code
<?php
include('../include/connect.php');
$control_no = "";
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$control_no = $_REQUEST['control_num'];
if(isset($_POST['subBtn']))
{
$control_no = mysql_real_escape_string($_POST["control_num"]);
$con->next_result();
$control_check_res = mysqli_query($con, "SELECT SUBSTRING(control_no, 1, 3) FROM tools_masterlist WHERE control_no = '$control_no'");
if (mysqli_num_rows($control_check_res))
{
echo '<script> $("#control_num_Modal").modal("show"); </script>';
}
else
{
$query = "INSERT INTO tools_masterlist (control_no)
VALUES ('$control_no')";
$con->next_result();
$result=mysqli_query($con,$query);
if(!$result)
{
echo '<script> $("#control_num_Modal").modal("show"); </script>';
}
else
{
echo '<script> $("#maModal").modal("show"); </script>';
}
}
}
}
?>
I have editted my code because I want to highlight the part where I coded my SUBSTRING query and the condition. I am really confused right now on what should I put in my condition thank you very much in advance for the help.
In your database, the column for "GTX" or that 3 unique character you are pertaining to, must be set in PRIMARY KEY so all data that is to be inserted is unique.

Printing single result from db2 query in php

I'm running a query on db2 in a php script, which is running successfully but I can't get it to echo the actual ID of the record I've selected. It does echo my success statement showing it ran successfully but I need the actual sessionid for comparison in another query.
Here I'm selecting the record, executing the query and checking for execution, but I'm also trying to use fetch_row and result to return the single selected ID:
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
$executeSessionMax = odbc_execute($prepareSessionMax);
while(odbc_fetch_row($executeSessionMax)){
$maxResult = odbc_result($executeSessionMax, "SESSIONID");
echo $maxResult;
}
How can I return the sessionID into a variable properly from db2?
You are passing the wrong parameter to the odbc_fetch_row() as $executeSessionMax is either a True or False depending on successful execution.
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
$executeSessionMax = odbc_execute($prepareSessionMax);
while(odbc_fetch_row($prepareSessionMax )){
// correction here ^^^^^^^^^^^^^^^^^^
$maxResult = odbc_result($executeSessionMax, "SESSIONID");
echo $maxResult;
}
You could recode as this specially as a MAX() will only ever return one row so the while loop is not needed either.
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$prepareSessionMax = odbc_prepare($DB2Conn, $latest_result);
if (odbc_execute($prepareSessionMax)) {
odbc_fetch_row($prepareSessionMax );
$maxResult = odbc_result($executeSessionMax, "SESSIONID");
echo $maxResult;
// if echo gets lost try writing to a file
error_log("maxResult = $maxResult", 3, "my-errors.log");
} else {
// something went wrong in the execute
}
You could also try
$latest_result = "SELECT MAX(SESSIONID) as SESSIONID FROM session";
$result = odbc_exec($DB2Conn, $latest_result);
$rows = odbc_fetch_object($result);
echo $row->SESSIONID;
$maxResult = $row->SESSIONID;

PHP Array to string to mysql - empty record

I am on point where I have to usk on forum.
So, I have an array that is my return from join table sql query.
i am displaying it correctly without the problem.
but some of those values I want to put in different table of mysql database.
$array = joint_table();
$array_value = array['key'];
I can echo array_value and it's displaying correctly, also checked variable type and it returns STRING.
however when I am inserting it into the table, it's empty cell.
I am inserting other stuff like date() and such and that is inserted correctly.
So my sql query works fine, besides I am using same query in other places without problem.
Only values I have from that array are not inserting, but still can echo them.
<?php
$page_title = 'Complete Task';
require_once('includes/load.php');
// Checkin What level user has permission to view this page
page_require_level(2);
$task = join_task_table((int)$_GET['id']);
?>
<?php
if(isset($_POST['complete_task'])){
$area = $task['area'] ;
$jig = $task['jig'];
$desc = $task['description'];
$freq = $task['freq'];
$date = make_date();
$user = current_user();
$user_done = remove_junk(ucfirst($user['name']));
$comment = remove_junk($db->escape($_POST['comment']));
if(empty($errors)){
$sql = "INSERT INTO tpm_history (area_name,jig_name,description,frequency,date_done,done_by_user,comment)";
$sql .= " VALUES ('{$area}','{$jig}','{$desc}','{$freq}','{$date}','{$user_done}','{$comment}')";
$result = $db->query($sql);
if($result && $db->affected_rows() === 1){
$session->msg('s',"Job Completed");
redirect('home.php', false);
} else {
$session->msg('d',' Sorry failed to complete the task!');
redirect('task_complete.php?id='.$task['id'], false);
}
} else{
$session->msg("d", $errors);
redirect('task_complete.php?id='.$task['id'],false);
}
}
?>
I am lost. Help.

Deleting records inside a foreach loop

I have an array that I am passing through a $_POST variable. In the foreach loop, I would like to check to see if "delete" has been checked. If so, I will delete the record. If delete is not checked, I will update the record. When I run this the update works perfect. If I have delete checked - it will delete the first record in the array - not the record with the corresponding id of the record with the checked box. If I have 2 checked - it will take the first 2. If I have them all checked - it will obviously then delete all the records. I have been wrestling with this one all day - looking for a little help. Thanks.
if (isset($_POST['update'])) {
$slo_id = $_POST['slo_id'];
foreach ($_POST['score_id'] as $key=>$score_id) {
$del = $_POST['del'][$key];
if ($del == 'checked') {
$sql2 = " DELETE FROM slo_score WHERE score_id = $score_id ";
#execute SQL statement
$result = mysql_query($sql2);
# check for error
if (mysql_error()) { print "Database ERROR in SQL Update Statement: " . mysql_error(); }
}
else {
$growth_target = $_POST['growth_target'][$key];
$final_score = $_POST['final_score'][$key];
$meets = $_POST['meets'][$key];
//update table
$sql1 = "UPDATE slo_score SET growth_target='$growth_target',final_score='$final_score',meets='$meets' WHERE score_id = $score_id";
#execute SQL statement
$result = mysql_query($sql1);
# check for error
if (mysql_error()) { print "Database ERROR in SQL Update Statement: " . mysql_error(); }
}
}
header("location:...);
}
try this
if (isset($_POST['update'])) {
$slo_id = $_POST['slo_id'];
foreach ($_POST['score_id'] as $key=>$score_id) {
if (isset($_POST['del'][$key])) {
//use mysqli to delete the record
}
else {
$growth_target = $_POST['growth_target'][$key];
$final_score = $_POST['final_score'][$key];
$meets = $_POST['meets'][$key];
//update table
use mysqli to update the record
}
}
header("location:...);
}
You should avoid looping deletes to MySQL at all costs.
If you are receiving an array of IDs to delete, why not just send that in one (or a few, if this is thousands of IDs we're talking about; chunk them) query:
$score_ids = isset($_POST['score_id']) ? $_POST['score_id'] : array();
$score_ids_in = implode("', '", $score_ids);
$sql = sprintf("DELETE FROM slo_score WHERE score_id IN ('%s')", $score_ids_in);
$result = mysql_query($sql);
Of course, this won't give you line by line feedback but it will keep your database from being choked to death.
Also, you already know you should use Mysqli to keep people from destroying your database, extracting sensitive data from it, or both. It's not a huge change from what you're doing now, except it's a lot more secure.

Give another random int if number exists in database (PHP)

I am trying to make a script to check if an int is already added to my database. If so, it will re-generate another random number and check again. If it doesn't exist, it'll insert into the database.
However, I am having troubles. If a number exists, it just prints out num exists, how would I re-loop it to check for another and then insert that? I have tried to use continue;, return true; and so on... Anyway, here is my code; hopefully someone can help me!
<?php
require_once("./inc/config.php");
$mynum = 1; // Note I am purposely setting this to one, so it will always turn true so the do {} while will be initiated.
echo "attempts: ---- ";
$check = $db->query("SELECT * FROM test WHERE num = $mynum")or die($db->error);
if($check->num_rows >= 1) {
do {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')")or die($db->error);
echo "$newnum - CAN INSERT#!#!#";
break;
}
} while(0);
}
?>
I think the logic you're looking for is basically this:
do {
$i = get_random_int();
} while(int_exists($i));
insert_into_db($i);
(It often helps to come up with some functions names to simplify things and understand what's really going on.)
Now just replace the pseudo functions with your code:
do {
$i = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $i")or die($db->error);
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
$db->query("INSERT test (num) VALUES ('$i')") or die($db->error);
Of course, you can do a little more tweaking, by shortening...
// ...
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
...to:
// ...
$int_exists = $newcheck->num_rows >= 1;
} while($int_exists);
(The result of the >= comparison is boolean, and as you can see, you can assign this value to a variable, too, which saves you 4 lines of code.)
Also, if you want to get further ahead, try to replace your database calls with actual, meaningful functions as I did in my first example.
This way, your code will become more readable, compact and reusable. And most important of all, this way you learn more about programming.
The logic is incorrect here. Your do-while loop will get executed only once (as it's an exit-controlled loop) and will stop on the next iteration as the while(0) condition is FALSE.
Try the following instead:
while($check->num_rows >= 1) {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if ($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')") or die($db->error);
echo "$newnum - CAN ISNERT#!#!#";
break;
}
}
Sidenote: As it currently stands, your query is vulnerable to SQL injection and could produce unexpected results. You should always escape user inputs. Have a look at this StackOverflow thread to learn how to prevent SQL injection.
Here is an example of some code that I threw together using some of my previously made scripts. You will notice a few changes compared to your code, but the concept should work just the same. Hope it helps.
In my example I would be pulling the database HOST,USER,PASSWORD and NAME from my included config file
require_once("./inc/config.php");
echo "attempts: ---- ";
$running = true;
while($running == true) {
//create random number from 1-5
$newnum = rand(1,5);
//connect to database
$mysqli = new mysqli(HOST, USER, PASSWORD, NAME);
//define our query
$sql = "SELECT * FROM `test` WHERE `num` = '".$$newnum."'";
//run our query
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//check results, if num_rows >= our number exists
if (mysqli_num_rows($check_res) >= 1){
echo $newnum . " exists! \n";
}
else { //our number does not yet exists in database
$sql = "INSERT INTO `test`(`num`) VALUES ('".$newnum."')";
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
if ($check_res){
echo $newnum . " - CAN ISNERT#!#!#";
// close connection to datbase
mysqli_close($mysqli);
}
else{
echo "failed to enter into database";
// close connection to database
mysqli_close($mysqli);
}
break;
}
}
I would also like to note that this will continue to run if all the numbers have been used, you may want to put in something to track when all numbers have been used, and cause a break to jump out of the loop.
Hope this helps!

Categories