The best way to run completely unrelated queries together? - php

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 ?>

Related

SQL query failing to INSERT new row into table

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

Allowing users to search database for username/email and showing results

I am trying to allow users to search a database and echo results, the thing is I want to search multiple tables. I know I can do SELECT * FROM x1, x2 but the rows are named something else so I cant
echo $row['username']
when the other row is username2. Maybe if its possible something like if($row == whatever), idk. Thanks for any help.
<?php
$search = $_POST['Srch'];
$host = "whatever";
$db = "whatever";
$user = "whatever";
$pwd = "whatever";
$link = mysqli_connect($host, $user, $pwd, $db);
$query = "SELECT * FROM users WHERE email LIKE '%$search%'";
$results = mysqli_query($link, $query);
if(isset($_POST['Srch'])) {
if(mysqli_num_rows($results) >= 0) {
while($row = mysqli_fetch_array($results)) {
echo "Username: " . $row['username'];
echo "Email: " . $row['email'];
}
}
}
?>
<body>
<form action="" method="POST">
<input type="Text" name="Srch">
<input type="Submit" name="Submit">
</form>
Edit: Found a way to do this. Something like this works:
function search1() {
// Search stuff here
}
function search2() {
// Search more stuff here
}
if(isset($_POST['Srch'])) {
search1();
search2();
}
If you want to search multiple tables you're going to have to join them somehow. Since you didn't post your table structure, I can only make assumptions on what you're trying to do, but the general syntax would be:
$query = "SELECT * FROM users u LEFT JOIN something s ON s.id = u.something_id WHERE u.email LIKE '%$search%'";
Then you can echo out the different columns that return. But again, this question needs more information for a better answer.
Hope this helps anyway!

Basic Php/Mysql Search: rowCount() returning error

I am developing a very basic php/mysql search. The search is based on a filter criteria of the value chosen in the dropdown menu. There are three options Whole Site, Pages, Blogs. In my php code I prepare the sql statements and then execute accordingly to the chosen filter. I am getting an error on $count = $query->rowCount() but most interesting when I try to echo the results from the query I am getting 1. How can I display the correct values and overcome the error? DEMO
PHP/Mysql
<?php
require("db_con/db_con.php");
$search_output = "";
if(isset($_POST['searchquery']) && $_POST['searchquery'] != ""){
$searchquery = preg_replace('#[^a-z 0-9?!]#i', '', $_POST['searchquery']);
if($_POST['filter1'] == "Whole Site"){
$sqlCommand = $db_con->prepare("(SELECT id, page_title AS title FROM pages WHERE MATCH (page_title,page_body) AGAINST ('$searchquery')) UNION (SELECT id, blog_title AS title FROM blog WHERE MATCH (blog_title,blog_body) AGAINST ('$searchquery'))");
} else if($_POST['filter1'] == "Pages"){
$sqlCommand = $db_con->prepare("SELECT id, page_title AS title FROM pages WHERE MATCH (page_title,page_body) AGAINST ('$searchquery')");
} else if($_POST['filter1'] == "Blog"){
$sqlCommand = $db_con->prepare("SELECT id, blog_title AS title FROM blog WHERE MATCH (blog_title,blog_body) AGAINST ('$searchquery')");
}
$query = $sqlCommand->execute();
$count = $query->rowCount();
if($count > 1){
$search_output .= "<hr />$count results for <strong>$searchquery</strong><hr />$sqlCommand<hr />";
$query->fetchAll();
foreach($row as $query){
$id = $row["id"];
$title = $row["title"];
$search_output .= "Item ID: $id - $title<br />";
} // close while
} else {
$search_output = "<hr />0 results for <strong>$searchquery</strong><hr />$sqlCommand";
}
}
?>
HTML
<h2>Search the Exercise Tables</h2>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Search For:
<input name="searchquery" type="text" size="44" maxlength="88">
Within:
<select name="filter1">
<option value="Whole Site">Whole Site</option>
<option value="Pages">Pages</option>
<option value="Blog">Blog</option>
</select>
<input name="myBtn" type="submit">
<br />
</form>
<div>
<?php echo $search_output; ?>
The rowCount() function only returns the number of rows affected by DELETE, INSERT, or UPDATE statements. To get a count of rows for a SELECT statement you have to do a separate query like this:
<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
} else { /* No rows matched -- do something else */
print "No rows matched the query.";
}
}
$res = null;
$conn = null;
?>
This is from the PHP manual, here:
http://ca2.php.net/manual/en/pdostatement.rowcount.php
Try $fetchColumn instead of $rowCount

PHP delete row via non PK

I have the user select a member ID, but I want it to delete the corresponding event ID (PK) so the row is just deleted. Can you suggest a simple and effective way of doing this? This is the code I am working on FYI.
Front end.
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
Select member ID to <b> remove total and comment. </b>: <select name="mid">
<?php
while($row = mysqli_fetch_assoc($result))
echo "<option value='{$row['mid']}'>{$row['mid']} </option>";
?>
</select>
<input type="submit" value=">!DELETE!<" />
</form>
<?php
}
else
{
$mid = $_POST['meid'];
$db1 = new dbme();
$db1->openDB();
$numofrows = $db1->delete_total($meid);//basically kill off the entire row
echo "Success. Number of rows affected:
<strong>{$numofrows}<strong>";
Back end method
function delete_total($mid, $meid) {
$sql = "DELETE FROM memberevent WHERE mid = $mid"; // This is the bit I am head scratching, might there be a way to use mid to identify the corresponding PK (meid) to delete so the entire row is killed?
$result = mysqli_query($this->conn, $sql);
if ($result) {
$numofrows = mysqli_affected_rows($this->conn);
return $numofrows;
}
else
$this->error_msg = "could not connect for some wierd reason";
return false ;
}
P.S I am aware it cannot work in its current form.
Here's the memberevent table structure.
meid (PK auto incr INT)
mid (int)
total (varchar)
comments (varchar)
ename (varchar)

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