SQL query failing to INSERT new row into table - php

I have a chunk of PHP code that triggers if a button is pressed by the user. What I expect to happen is it checks to see if the user has the skill already assigned to them, and if not it performs an INSERT. Then if it does do nothing. And finally if the checkbox next to a skill is un-checked it checks to see if they have the skill already assigned and delete it if found.
The code is deleting the skills from the user no matter the condition of the checkboxes. Im sure I must be missing something but after starring at the code for hours I cannot see it.
Can anyone suggest a resolution?
PHP code:
if(isset($_POST['Update']))
{
$default = 0;
foreach($skills_array AS $skills_id=>$skills_name)
{
if (isset($_POST[$skills_name]))
{
if (empty($_POST[$skills_name.'exp']))
{
$exp = $default;
}
else
{
$exp = $_POST[$skills_name.'exp'];
}
$sql = $con->query("SELECT count(`UserID`) as total FROM `userskills` WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
if ($row = mysqli_fetch_assoc($sql))
{
$sql = $con->query("INSERT INTO `userskills` ( `UserID`, `SkillID`, `Experience`) VALUES ('$User', '$skills_id', '$exp')")
or die(mysqli_error($con));
//If the checkbox is not checked it will check to see if skill is already a skill assigned to the user. If they are it will delete it. If not it will ignore.
}
else
{
$sql = $con->query("UPDATE `userskills` SET `Experience` = '$exp' WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
}
}
else
{
$sql = $con->query("DELETE FROM `userskills` WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
}
}
header('Location: Account.php');
die();
}
else
{
echo 'Incorrect password please try again.';
}
}
HTML Code:
<div class="RightBody">
<form id="form2" name="form2" method="post" enctype="multipart/form-data">
<p><h3>Skills:</h3>
<?php
$result1 = $con->query("SELECT skills.`SkillID`, skills.`Description`, COUNT(userskills.`SkillID`) AS SkillUserHas, MAX(`Experience`) AS Experience
FROM `skills`
LEFT OUTER JOIN userskills
ON skills.`SkillID` = userskills.`SkillID` AND userskills.`UserID` = '$User'
GROUP BY skills.`SkillID`, skills.`Description`
ORDER BY FIELD(skills.`SkillID`, 1, 7, 9, 3, 4, 5, 6, 8)")
or die(mysqli_error($con));
while ($skillrow = $result1->fetch_assoc())
{
?>
<div class="CheckboxText">
<?php
echo '<label>';
echo '<input type="checkbox" name="'.$skillrow['Description'].'" id="CheckboxGroup1_'.$skillrow['SkillID'].'" class="skillselect" value="yes" '.(($skillrow['SkillUserHas'] > 0) ? 'checked' : '').'>';
echo $skillrow['Description'].'</label>';
echo '<input type="number" name="'.$skillrow['Description'].'exp" class="expnumber" placeholder="Enter Experience in years." value="'.$skillrow['Experience'].'">';
echo '<br />';
echo '<br />';
}
?>
</div>
</p>
</form>
</div>

Im not familiar with PHP, but yesterday I help in a similar problem
Here you create your query but your COUNT will always return a row, and if not skill the value is 0
$sql = $con->query("SELECT count(`UserID`) as total FROM `userskills` WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
So instead of if ($row = mysqli_fetch_assoc($sql)) you need something like
$row = mysqli_fetch_assoc($sql);
$skill = $row['total'];
if ($skill == 0 )
But that doesnt solve the error you describe, delete all skills or just the one selected?
Any way you have to check this IF that is the branch sending your skill to delete.
if (isset($_POST[$skills_name]))
This mean your $skills_name isnt defined. Maybe you should check for the value inside the array $skills_array?
My second guess check the code create on the webpage. Right click your page and selece see source code

Related

Select the updated value using PHP

I'm working on attendance base on login and logout, Is there a way I can make this code work, I'm having a problem on after successfully update the data it will go to another notepad and in there it has a select query that will display the image and basic info of user. But when I tried to logout it displays different user info and images.
Here is my code for php:
<?php
include_once ('connection.php');
if(isset($_POST['submit']))
{
$username2 = $_POST['username2'];
$password1= $_POST['password1'];
$time=date("H:i:s");
$sql = mysqli_query($conn,"SELECT tbl_visitor.Birthday,tbl_visitor.School_Company,tbl_visitor.Contact_number,tbl_visitor.Visitor_Address,tbl_visitor.image,tbl_visitor.Visitor_username,tbl_visitor.Visitor_id,tbl_visitor.Visitor_password,concat(Visitor_first_name,'',Visitor_last_name) as name,
tbl_visitor_form.Time_in,tbl_visitor_form.Time_out , tbl_visitor_form.Number FROM tbl_visitor LEFT JOIN tbl_visitor_form on tbl_visitor.Visitor_id = tbl_visitor_form.Visitor_id WHERE tbl_visitor.Visitor_username = '$username2' and tbl_visitor.Visitor_password = '$password1'
order by Number DESC limit 1");
$count = mysqli_num_rows($sql);
if ($count == 0) {
$_SESSION['error_message'] = "Incorrect username or password";
header("Location:logout.php?");
} else{
while ($row = mysqli_fetch_array($sql)) {
$username2 = $row['Visitor_username'];
$password1 = $row['Visitor_password'];
$name=$row['name'];
$id=$row['Visitor_id'];
$image=$row['image'];
if(empty($row['Time_in'])) {
header("location:visitorvalidate1.php");
} else if(empty($row['Time_out'])){
$InsertSql = "Update tbl_visitor_form set Time_out = '$time' where Visitor_username='$username2' and Visitor_password = '$password1' order by Number DESC limit 1 ";
$res = mysqli_query($conn, $InsertSql);
header("location:outsuccess.php?");
}else{
header("location:visitorvalidate1.php");
}
}
}
}
?>
here is my outsuccess.php:
<?php
include_once('connection.php');
$sql = "select Visitor_username, image, Visitor_name from tbl_visitor_form
order by Number DESC limit 1 ";
$result = mysqli_query($conn,$sql);
while( $row = mysqli_fetch_array($result)) {
$uname=$row['Visitor_username'];
$name=$row['Visitor_name'];
$image=$row['image'];
}
?>
the first query above is working but the second query in select has the problem, it selects different value after the update. for example, there is two user has already login user1 and user2 when I try to logout user1 it successfully updated but it displays the info of user2 instead of user1 on outsuccess.php. Hope you can help me fix this. Advance Thanks

Show error message when clicked on the like button

Hello I want to make a like system using PHP and MySQL when clicked on the like Button i also insert Data in the database but there is an error database value inserted but like value as 0 no increment and undefined error occurs . Can anybody help me solving this problem
There is my Like button code :
<?php
//// work with like box
$get_likes = mysqli_query($con,"SELECT * FROM `likes`");
if (mysqli_num_rows($get_likes)===1) {
$get = mysqli_fetch_assoc($get_likes);
// $uid = $get['uid'];
$total_likes = $get['total_likes'];
//echo $uid;
$total_likes = $total_likes + 1;
//echo $total_likes++;
}
if (isset($_POST['likebutton_'])) {
$like = mysqli_query($con,"UPDATE `likes` SET `total_likes` = '$total_likes'") or die(mysqli_error($con));
//$insert_Data = mysqli_query($con,"INSERT INTO `likes` (`uid`) VALUES('$username')") or die(mysqli_error($ocn));
header("Location:home.php");
}
else
{
echo "Error";
}
?>
this code work fine without insert Data
There is My liked with Data Insertd Code
<?php
////work with like box
$get_likes = mysqli_query($con,"SELECT * FROM `likes`");
if (mysqli_num_rows($get_likes)===1) {
$get = mysqli_fetch_assoc($get_likes);
// $uid = $get['uid'];
$total_likes = $get['total_likes'];
//echo $uid;
$total_likes = $total_likes + 1;
//echo $total_likes++;
}
if (isset($_POST['likebutton_'])) {
$like = mysqli_query($con,"UPDATE `likes` SET `total_likes` = '$total_likes'") or die(mysqli_error($con));
$insert_Data = mysqli_query($con,"INSERT INTO `likes` (`uid`) VALUES('$username')") or die(mysqli_error($ocn));
header("Location:home.php");
}
else
{
echo "Error";
}
?>
this is output i want to display my font-end page <?php echo $total_likes ;?> but it occur error
The error is Undefined Variable
I also try $total_likes="";
as global but still not work
Your code suffers from a race condition. What you should be doing is this pattern:
INSERT INTO likes (uid, total_likes) VALUES (?, 1)
ON DUPLICATE KEY SET total_likes=total_likes+1
Where you use bind_param to set the placeholder value to your UID.
Note that in your one query you set the total count of all likes to be +1. This is a huge mistake.

The best way to run completely unrelated queries together?

I seem to be running into this issue often, usually for checking to see if a $_GET['id'] actually exists in my database before running another query, related or not to the id being received.
If a record exists with the same id, then I show the HTML, e.g.:
if ($r) { #query was successful
$num = mysqli_num_rows($r);
if ($num == 1) {
?>
<form method="post">
...
<input type="submit" value="Submit" />
</form>
<?php
} else {
echo 'No records';
}
} else {
echo 'Query Failed';
}
mysqli_free_result($r);
The above works, but let's say that I want to perform another unrelated query between my opening/closing form tags; would it be proper to simply do something like this, which I would consider a nested query:
$q = "SELECT id FROM stuff WHERE id = $id";
$r = #mysqli_query($dbc, $q);
if ($r) { #query was successful
$num = mysqli_num_rows($r);
if ($num == 1) {
?>
<form method="post">
<?php
$q = "SELECT example FROM somewhere";
$r = #mysqli_query($dbc, $q);
if ($r) {
$num = mysqli_num_rows($r);
if ($num > 0) {
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo $row['example'];
}
}
} else {
echo 'Query failed';
}
?>
<input type="submit" value="Submit" />
</form>
<?php
} else {
echo 'No records';
}
} else {
echo 'Query Failed';
}
mysqli_free_result($r);
Or maybe create a boolean, like so:
$id_status = 0;
$q = "SELECT id FROM stuff WHERE id = $id";
$r = #mysqli_query($dbc, $q);
if ($r) { #query was successful
$num = mysqli_num_rows($r);
if ($num == 1) {
$id_status = 1;
}
}
mysqli_free_result($r);
if ($id_status) { #Run another query
...
}
I currently have a problem when it comes to requiring two separate query results for one task: (1) generating inputs from another table, (2) displaying the current values, (3) checking to see what input that has been generated matches the current value, e.g.:
$q = "SELECT id, food FROM restaurants";
$q = "SELECT favFood FROM people WHERE id = 1"; #favFood is equal to the id of food
...
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
?>
#generate all food from table, make favFood the current selected input
<input type="radio" name="yum" value="<?php echo $row['id']; ?>" />
<?php
}
So as you can see, I am having trouble when it comes to unrelated queries; the last example would probably work with a UNION or something, but i'd have a bunch of repeated rows displaying favFood, so it doesn't feel right, e.g.:
favFood | id | food
1 | 1 | Pizza
1 | 2 | Burgers
1 | 3 | Monkey Brains
Before I end this, I just want to say that I have made an attempt to use mysqli_multi_query, but I most likely did something wrong; i'm not even sure if it would work in this case, or what it does exactly.
Thanks!
If you want to check whether a record exists multiple times in your code, I suggest to create a function which returns a bool.
function record_exists($dbc, $q){
$state = false;
if($r = #mysqli_query($dbc, $q)){
if(mysqli_num_rows($r) == 1){
$state = true;
}
mysqli_free_result($r);
}
return $state;
}
$q = "SELECT id FROM stuff WHERE id = $id";
if(record_exists($dbc, $q)){
echo 'Yay, it exists';
}
Then if you want to SELECT some fields from a table but the filter depends on a value from another table, you could JOIN two tables in the query like so:
SELECT restaurants.id, restaurants.food
FROM restaurants
JOIN people ON restaurants.id = people.favFood
WHERE people.id = 1
Now you only SELECT the fields you want from table restaurants and filter them on a person id from the table people.
Two reasons why you've got such a problem
You are doing A LOT of useless stuff.
no one needs you "query failed" statement.
num rows check is also superfluous
most of the code you write is just repetitions
Like PHP users from the last century you are mixing database calls with HTML output. Now you see that the term "spaghetti code" was coined for a reason.
Your database related code rewritten with simple mysqli wrapper:
$rows = [];
$found = $db->getOne("SELECT id FROM stuff WHERE id = ?i", $id);
if ($found) {
$rows = $db->getAll("SELECT example FROM somewhere");
}
Now you can proceed to HTML output, either inline or (better) by including a template
?>
<?php if ($rows): ?>
<form method="post">
<?php foreach ($rows as $row): ?>
<?=$row['example']?>
<?php endforeach ?>
<input type="submit" value="Submit" />
</form>
<?php else: ?>
No records
<?php endif ?>

Need to update one row in database

I am making an application and need to update only one row in my database. The way I build the application it updates all my rows in the database. Could someone look in my script and tell me how i can update one row?
I know i need to do something with id's but i dont know how..
Here is the script for the page where users can change the data from the database. In this way every record will update.
<section>
<?php
$sql = "SELECT naam, plaats.plaats, type.type, status FROM devices, type, plaats, status
WHERE devices.type_id = type.type_id
AND plaats.plaats_id = devices.plaats_id
AND status.status_id = devices.status_id
AND plaats.plaats ='benedenverdieping'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
echo '<table><tr><td>Naam</td><td>Plaats</td><td>Type</td><td>Status</td><td>open/dicht</td><td>Submit</td></tr>';
while($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>' .$row['naam']. '</td>';
echo '<td>' .$row['plaats']. '</td>';
echo '<td>' .$row['type']. '</td>';
echo '<td>' .$row['status']. '</td>';
echo '<td>';?>
<form action="opendicht.php" method="post">
<select name="opendicht">
<option name="open" value="1">open</option>
<option name="dicht" value="2">dicht</option>
</select>
<?php '</td>';
echo '<td>'?>
<input type="submit" value="Doorvoeren" name="submit">
</form>
<?php '</td>';
}
echo '</table>';
}
?>
</section>
Here is the script which execute the users input. Because of the sql query's it wont work for only one record. The way it works right now is the query updates every record with status_id 1 or 2. In the database the 1 stands for open and the 2 stands for closed. I can't find a way to let the query update only one row of data.
<?php
session_start();
$naam = $_SESSION['username'];
echo $naam;
include '../dbconnect.php';
date_default_timezone_set("Europe/Amsterdam");
$t=time();
$aanpassing = date("d-m-y h:i",$t);
$sel_device_id = ("SELECT device_id FROM devices");
$run_device_id = mysqli_query($con, $sel_device_id);
if(isset($_POST['submit']))
{ // Fetching variables of the form which travels in URL
$opendicht = $_POST['opendicht'];
if($opendicht =='1')
{
//UPDATE devices SET status_id = $opendicht, username = (SELECT user_id FROM users WHERE username = '$naam'), timestamp = '$timestamp' WHERE status_id = '2'
mysqli_query($con,"UPDATE devices SET status_id = $opendicht, username = '$naam', tijd = '$aanpassing' WHERE status_id = 2");
}
else
{
mysqli_query($con,"UPDATE devices SET status_id = $opendicht, username = '$naam', tijd = '$aanpassing' WHERE status_id = 1");
}
}
else{
echo "er is iets fout gegaan";
}
mysqli_close($con); // Closing Connection with Server
header( "refresh:0;url=index.php" );
?>
These are your UPDATE queries:
mysqli_query($con,"UPDATE devices SET status_id = $opendicht, username = '$naam', tijd = '$aanpassing' WHERE status_id = 1");
mysqli_query($con,"UPDATE devices SET status_id = $opendicht, username = '$naam', tijd = '$aanpassing' WHERE status_id = 2");
You're updating all the rows where the status_id is 1 or 2.
You need to add an AND condition to identify the unique row identifier to update.

Delete database entry if checkbox is unchecked

I have a form that allows engineers to be added to a job by checking checkboxes which works fine. However, I would like the user to remove an engineer by unchecking their checkbox on another form.
The table (a many to many table) has 3 columns id_ce (the primary key), call_ce (foreign key) and engineer_ce (foreign key). I would like the form to check if a checkbox is empty and if it is check to see if there is an entry in the table with the call_ce and engineer_ce and delete it if it exists but I'm failing miserably.
This is what I have so far...
foreach($_POST['engineer'] as $engineer_id){
if(!isset($_POST['engineer'])){
$sql = "SELECT * FROM calls_engineers WHERE call_ce = '$diary_id' AND engineer_ce = '$engineer_id'";
$result = mysql_query($sql)or die(mysql_error());
if(mysql_num_rows($result) > 0){
$sql = "DELETE FROM calls_engineers WHERE engineer_ce = '$engineer_id'";
$result = mysql_query($sql)or die(mysql_error());
}
}
}
I suspect the problem may be something like the checkboxes that aren't checked don't post so they aren't going through the foreach loop but I'm not sure of another way of doing it.
Any help will be greatly appreciated
You can put on page a hidden field with engineer ids. Say, it will be called engineer_on_page
Now you can
foreach($_POST['engineer_on_page'] as $engineer_id) {
if(!in_array($engineer_id, $_POST['engineer'])){
//do delete here
}
}
I expect that checkboxes looks similar to this:
<input type="checkbox" name="engineer[]" value="[engineer_id]"/>
and hidden field
<input type="hidden" name="engineer_on_page[]" value="[engineer_id]"/>
Also you may specify checkbox field like this:
<input type="checkbox" name="engineer[[engineer_id]]" value="[engineer_id]"/>
where [engineer_id] is actual id (1, 2,3 etc)
In second case you may use
if(!isset($_POST['engineer'][$engineer_id])){
//do delete here
}
/* BY ROHIT BHAYAL */
$checkbox1=$_POST['stu2'];
$chk="";
/* print_r($_POST['stu3']); */
$order1=$_POST['stu3'];
if(isset($_POST['subject']))
{
$string = implode(',', $checkbox1);
echo $del="delete from student_subject where sub_id not in ($string)";
mysql_query($del);
}
// mysql_query($del);
foreach ($checkbox1 as $key => $chk1)
{
$chk .= $chk1.",";
$check="SELECT * FROM student_subject WHERE sub_id = '".$chk1."' AND form_id='".$_GET['sub']."'";
$rs = mysql_query($check);
$data = mysql_fetch_array($rs);
mysql_num_rows($rs);
if($data[0] > 1)
{
echo "Subject is Already Exists<br/>";
}
else
{
if(isset($_POST['subject']))
{
$a= "sub_id='".$chk1."'";
echo $ins = "insert into student_subject set form_id='".$_POST['stu1']."',
".$a.",
order_no='".$chk1."'";
}
if (mysql_query($ins))
{
echo "Now New subject Is Added<br/>";
}
else
{
echo "Error adding user in database<br/>";
}
}
}
?>

Categories