Run SQL Query with button click - php

Edit 3: I figured I should try to word, not only my issue but also my end goal better... so here it goes. I need data to be returned to the user by their input. What they put into the form, will return specific data from the database or nothing at all. The database I'm using is information on field reps. When the user enters into the form, they will be looking for specific information. The number they will be asked for will be the repID number. Now... the problem I am having is taking the number that is put into the form, and calling that specific data from the database. The user will not be able to see other data, not associated with other repID's.
Okay, I'm pretty sure I'm not supposed to just delete my entire initial post, but I'm still searching for an answer. Now, I would assume it should be relatively simple, however it has turned out to more taxing than I had originally thought. Perhaps I am not explaining my needs clear enough, I do tend to have that issue a lot.
Here it goes... How to Run sql Query with button click 2.0:
I have a database written in sql and stored on a server. The table I will be accessing is called dataRep and houses Rep Data. This data is user input via form submission. Upon coming to the website there is an option to "View Rep Information" by submitting the Rep's ID that was given. That Rep ID will be the auto increment repID from the table. Upon clicking the button, it opens a new window that should display the rep's data. It does not, however.
Here is the html the user will see:
<div class="pop_box">
<a class="rms-button" href="#popup1">Enter Rep Number Here</a> </div>
<div id="popup1" class="overlay">
<div class="popup">
<a class="close" href="#">×</a>
<div align="center"><br>
<br>
<p>Enter rep number in box below. Submission will open new window.</p>
<form method="get" action="/data/repPrepare.php" target="_blank" >
<input type="text" id="repSelect" name="repSelect" placeholder="Enter Rep Number Given Here" />
<button type="submit" class="newbutton">VIEW</button>
</form>
</div>
</div>
...changed the php a little, but now I get this error:
"Warning: mysqli_query() expects at least 2 parameters, 1 given on line 21
Unable to prepare statement: Query was empty"
<?php
$host = 'mhhost';
$user = 'myuser';
$pass = 'mypass';
$db = 'mydatabase';
$con = mysqli_connect($host,$user,$pass, $db);
//-------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$query = mysqli_query("SELECT * FROM dataRep WHERE repID = ?"); //query
$stmt = mysqli_prepare($con, $query)
or die("Unable to prepare statement: " . $con->error);
$stmt->bind_param("i", $_GET["repSelect"]);
$stmt->execute();
$array = mysqli_fetch_row($result); //fetch result
//-------------------------------------------------------------------------
// 3) echo result as json
//-------------------------------------------------------------------------
echo json_encode($array);
?>
I would like to apologize in advance if I'm totally messing up the procedure for the forum, its just I am truly stuck and have been dealing with this issue for two weeks. Once again, I would appreciate any assistance that can be provided. I just need the php to pull the data tied the repID that the user puts in the box (repSelect).

try like this. You have to print variables bind in bind_result().So
<?php
$stmt = $mysqli->prepare("SELECT repID, RepName, RepBio, RepCerts FROM dataRep WHERE repID = ?");
$stmt->bind_param('i', $_GET['repSelect']);
$stmt->execute();
$stmt->bind_result($repID, $repName,$repBio,$repCerts);
while($stmt->fetch()){
echo $repName;//now it prints RepName
};
$stmt->close();
?>

Related

Why does the DataBase return old information?

(Edit: I added examples below. I also added a public_ip to my tables as suggested in the comments)
(Just a disclaimer, I am still very new to web development. I especially know very little about MySQL in conjuction with PhP.)
I have a database table that contains a number records. For this example it contains records of DVDs. One of my php pages receives the ID of the DVD to be removed, and then proceeds to do so. ($chosenTable is a variable as I also have different tables for CDs, Vinyls and others - they all have the same columns)
$sql = "DELETE FROM $chosenTable WHERE id=$removeID";
$conn->exec($sql);
Yet I've noticed that recently it would delete non-existing records.
For example, I would have this in my database:
ID - Title - Comment - File location
1 - Mr Bones - Very new - Folder/Bones.jpg
2 - Avengers - Secondhand - Folder/Avengers.jpg
Using the delete query works the first time. If I send "2", it removes record two. So as expected I have one record left:
ID - Title - Comment - File location
1 - Mr Bones - Very new - Folder/Bones.jpg
I would then add a new record. From the database on phpMyAdmin I am absolutely sure it has been added:
ID - Title - Comment - File location
1 - Mr Bones - Very new - Folder/Bones.jpg
2 - Intersteller - Broken - Folder/Intersteller.jpg
But here is where I am left without any explanation. If I remove the second record again (this time Intersteller), then nothing happens. When I checked the Title given of the record it is supposed to delete, it returns the title of the old second record.
Getting the info of the record I want to delete:
$temp = $conn->query("SELECT Title from $chosenTable WHERE ID='$removeID')->fetch()["Title"];
echo $temp;
When I did this it returns Avengers. With the above example in mind, the title being returned is supposed to be Intersteller, NOT Avengers. Avengers no longer exists in the table. I am absolutely sure about this. So now I know that it doesn't delete the second record (Intersteller), because it is deleting the OLD second record, Avengers. The same applies when I delete the third or fourth records (it instead deletes the non-existing old third and fourth records).
It seems for some reason Chrome or the server has its own pseudo-table stored somewhere that it uses instead of my actual table.
I have looked all day and I cannot find a solution this. I apologize again for any stupid mistakes. I just really wish I could understand how on earth I could get past this.
I noticed when I use another browser, like Firefox or even my smartphone's browser, it again allows me to remove a record once. I then have the exact same problem if I upload and remove another item. That it happens on different browsers makes me think the problem lies with me.
I am using Database MySQL client version: 5.6.43
Any help at all?
Edit: I made two php pages to simulate the problem. The same thing happens. I do not know how to connect to DB fiddle so I hope the code itself will suffice. upload.php submits information and adds it to the database table. remove.php removes record one of the table:
upload.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
//Get info from POST
$uTitle = $_POST["iTitle"];
$uComment = $_POST["tComment"];
$uPrice = $_POST["iPrice"];
echo "<script>console.log('$uTitel - $uComment - $uPrice);</script>";
//Set a file location for the uploaded picture
$fileName = basename($_FILES["iFile"]["name"]);
echo "<script>console.log('filenaam: $fileName');</script>";
$saveLocation = "uploads/".$fileName;
echo "<script>console.log('Saved locationk: $saveLocation');</script>";
//Upload file
if (move_uploaded_file($_FILES["iFile"]["tmp_name"], $saveLocation))
{
//If file is successfully uploaded
echo "<script>console.log('File uploaded');</script>";
//For connecting to database table - these four variables obviously just for illustration:
$servername = "localhost";
$connectusername = "alyosha";
$connectpassword = "alyoshaPassword";
$dbname = "alyoshaDB";
try { //If connected to database
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $connectusername, $connectpassword);
echo "<script>console.log('Connected to Database');</script>";
//I first see how many records are already in the table so that I can add the appropriate value for my 'public_ip' column
$m = $conn->prepare("SELECT * from testTable");
$m->execute();
$amountRows = $m->rowCount();
echo "<script>console.log('Amount in table before adding record: $amountRows');</script>";
//newIP is the current amount+1 so that it is added below my previous records (if there are 3 records, the new one should obviously be record public_ip 4)
$newIP = $amountRows +1;
//Now for adding a row to the table with the submitted informaton:
$sql = "INSERT INTO testTable (public_ip, Title, Comment, Price, File_Location) VALUES ($newIP, '$uTitle', '$uComment', $uPrice, '$saveLocation')";
$conn->exec($sql);
echo "<script>console.log('New row added');</script>";
//Count again to make sure there is one more record than before
$m = $conn->prepare("SELECT * from testTable");
$m->execute();
$amountRows = $m->rowCount();
echo "<script>console.log('Amount in table after adding record: $amountRows');</script>";
}
catch (PDOException $e){ //if database did not connect
echo "<script>console.log('Failed to connect to database');</script>";
}
}//if move
}//if post
?>
<!DOCTYPE html>
<html>
<head>
<title>Add item</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
<header>
<h1>Upload</h1>
</header>
<form action='upload.php' method='post' enctype='multipart/form-data'>
<input type='file' name='iFile' required>
<br/>
<br/>
<label for='iTitle'>Title:</label>
<input type='text' name='iTitle' required>
<br/>
<br/>
<label for='iPrice'>Price:</label>
<input id='iPriceUpload' type='number' name='iPrice' min='1' required>
<br/>
<br/>
<label for='tComment'>Comments (optional):</label>
<br/>
<textarea type='text' name='tComment'></textarea>
<br/>
<br/>
<input type='reset' name='iReset'>
<input type='submit' name='iSubmit'>
<br/>
<a href='remove.php?num=1'>Remove record 1</a>
<!--In practise the user would not be able to choose this by altering the link, but for my example this is easier to change this here -->
</body>
</html>
remove.php:
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET"){
$removeIP = $_GET["num"]; //The public_ip record to be deleted
//Connect to table
servername = "localhost";
$connectusername = "alyosha";
$connectpassword = "alyoshaPassword";
$dbname = "alyoshaDB";
try { //If connected to database
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $connectusername, $connectpassword);
echo "<script>console.log('Connected to Database in Remove.php');</script>";
//All the remaining records should have their public_ips shifted upwards (5->4, 4->3, 3->2, 2->1)
//It is necessary to again count the amount of rows left to achieve this
$m = $conn->prepare("SELECT * from testTable");
$m->execute();
$amountRows = $m->rowCount();
echo "<script>console.log('Amount of rows before deleting: $amountRows');</script>";
//For debugging purposes get the title of removeIP:
$gotTitle = $conn->query("SELECT Title from testTable WHERE public_ip='$removeIP'")->fetch()["Title"];
echo "<script>console.log('Title of record $removeIP to be deleted: $gotTitle');</script>";
//
$sql = "DELETE FROM testTable WHERE public_ip=$removeIP"; //public_ip=1
$conn->exec($sql);
echo "<script>console.log('Record $removeIP deleted');</script>";
//count again to make sure one record is removed:
$m = $conn->prepare("SELECT * from testTable");
$m->execute();
$amountRows = $m->rowCount();
echo "<script>console.log('Amount of rows affter deleting: $amountRows');</script>";
if ($removeIP < ($amountRows+1)){ //in case the removed record is the only one in the table it won't be necessary to change the public_ips of the rest
for ($x = 1; $x < ($amountRows+2); $x++)
{
echo "<script>console.log('Changing record: $x');</script>";
$lowerIP = $x-1; //The record with public_ip 2 should become public_ip 1, and 3->2, etc
$sql = "UPDATE testTable SET public_ip=$lowerIP WHERE public_ip=$x";
$stmt = $conn->prepare($sql);
$stmt->execute();
}
echo "<script>console.log('Loop finished');</script>";
}
}
catch (PDOException $e){
echo "<script>console.log('Failed to connect to database in Remove.php');</script>";
}
}//if GET
//After everything go back to upload page
echo "<script>window.location = 'upload.php';</script>";
?>
Here's a screenshot of the type of table I'm using:
UPDATE: From extensive comments it seems something somewhere between the PHP and and browser is caching the pages. #Martin proposed a workaround which seems to be very helpful until I solve this issue. This is adding a date string to the page urls, forcing the browser to read a new a page rather than a cached page (if I understand this correctly).
But if someone could still explain why this is a problem in the first place I would really appreciate it. I can understand the browser or whatever using an old version of the page, but I cannot understand whatever this is keeping an outdated table somewhere.
With respect, this business of renumbering your rows when you delete one is a really bad idea.
Why?
For one thing, the cost of doing this goes up the more rows you have. And the whole point of SQL is to allow you to handle vast tables efficiently.
For another thing, when you have multiple users doing this you get confusion. If one user is looking things up while another is deleting them, the first user will have the row numbers change under her. You can manage this with judicious use of database transactions, but they'll just block the second user until the first is done. This situation is often called a "race condition."
You mentioned you're new to MySql. Again with respect, I suggest you stick to the tried-and-true way of handling your ID numbers: auto-incrementing. When you delete a row from an auto incrementing table, the next row inserted does not re-use the deleted ID.
Everybody uses autoincremented ID values--from students to credit-card companies with unimaginably vast tables. I suggest you do the same, at least until you get a little more proficient with the technology.
Edit If you want to display your rows in the order you inserted them, simply do SELECT whatever FROM tbl ORDER BY id where id is the autoincrementing ID column. Gaps in the sequence of IDs due to deleted rows are not a problem.
If you have a particular ID value and you want the next row, in the order you inserted them, you can do
SELECT whatever
FROM tbl
WHERE id > <<<the value you have>>
ORDER BY id
LIMIT 1;
The id > <<<the value you have>> filter works even with gaps in the ID values.
You say there's only one user. But if that user happens to have two web pages open working on the database at the same time, your renumbering setup will fail. Spectacularly. When you have a web interface, it's always safest to assume you will have concurrent access.

How to allow users to search my database from a WordPress web page

I have a database of some entities (to warn people from them, scan fraud, etc.) and provide a search box when some one searches.
It will tell him if this entity is included in this fraud list, and why to show for an example a source of the warning if no source it won't show it
I'm so confused I can't even start, should it be just normal listing and user can just do ctrl + f... or I have to do it more creatively
First you haven't provided a structure of the database so I added some example colums like websitename, url and added_at
You first need a Database connection
$pdo = new PDO("mysql:hostname=localhost;dbname=fraud"; "mysqlusername, "mysqlpassword");
Then you need a search form
<form action="index.php?search=1" method="GET">
Search query: <input type="text" name="query"><br>
<input type="submit"><br>
</form>
After that you need to get the entries from the MySQL Database.
if(isset($_GET["search"])) {
$stmnt = $pdo->prepare("SELECT * FROM table WHERE websitename = ? OR url = ?");
$stmnt->execute(array($_GET["query"], $_GET["query"]));
// Print values
while($row = $stmnt->fetch()) {
echo $row["websitename"];
echo $row["url"];
echo $row["added_at"];
}
}

Insert the next highest value in the database using php

Imagine I have a data in the database named warehouse and a whID for the warehouse number. In my add.php I have a form where when you click the submit button, it will add whID data higher than the whID number in the database without using auto increment. I'ved tried a few code for this but nothing works.
this is my code in add.php:
<form action="sidenav/function.php" method="post">
<button type="submit" name="submit" class="button">Add</button>
</form>
This is my code for the function of form in add.php:
if (!isset($_POST['submit'])) {
$insert = $conn->prepare("INSERT INTO warehouse (whID) VALUES (?)");
$insert->bind_param('i', $whNumber);
if ($insert->execute()) {
header('Location: ../warehouseList.php');
die();
}
Sorry for my bad English, I hope you understand my question. Thank you!
If you don't want to use auto-increment just get the highest id from database and increment it yourself.
Quick and dirty example:
$stmt = $conn->prepare("SELECT MAX(whID) as id FROM warehouse LIMIT 1");
$stmt->execute();
$row = $stmt->fetch();
$id = $row["id"] + 1;
Anyway I recommend you to use auto-increment on the id. That's a scenario for what it's created for.

Re-populating / Editing HTML form inputs using MySQL Data

Being new to PHP and SQL, I have build a simple HTML form with 20 inputs, allowing users to enter specific data through input type=text or file. I have built a mysql database where this user data is inserted / saved. All is working, this is a major accomplishment for me.
I'm asking for help on this next step, I think this step would be called “edit”?
This step would allow users to recall the mysql data they entered, at a later time, to edit and save. Would like to have this recalled data injected directly into the original HTML form. Now, it seems necessary to have a method, (possibly a HTML form ”id “input), that calls from the data base, the specific record (including all 20 data inputs) that is associated with this user. Am I thinking correctly?
I'm asking for help / direction with simple yet detailed approach to solve this step. Note, my few attempts at this “edit” step, using some examples, have failed. I do not have a firm grasp of this PHP, yet have strong desire to become proficient.
This is a model, stripped down version of my current working code. I eliminated the $connection = mysql_connect.
This is the PHP I built, working great!
<?php
require('db.php');
if (isset($_POST['first_name'])){
$first_name = $_POST['first_name'];
$favorite_color = $_POST['favorite_color'];
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `form_data` (first_name, favorite_color, trn_date) VALUES ('$first_name', '$favorite_color', '$trn_date')";
$result = mysql_query($query);
if($result){
echo "<div class='form'><h1>First Name & Favorite Color POST to db was successfull.</h1>
<br/><h3>Click here to return <a href='https://jakursmu.com/tapcon_builder/tb_form_data_1.1.php'>TapCon Builder</a></h3>
</div>";
}
}else{
?>
This is the HTML user form, works great with the PHP script:
<div class="form">
<h1>First Name & Favorite Color "POST" to db Test</h1>
<form target="_blank" name="registration" action=" " method="post">
<p> First Name<input name="first_name" type="text" placeholder="First Name" /> </p>
<p> Favorite Color <input name="favorite_color" type="text" placeholder="Favorite Color" /> </p>
<p> <input type="submit" name="submit" value="Submit / Update to db" /></p>
</form>
</div>
Suppose the user queries the database using their “first_name”, when this “edit” step is completed, the final result will render / inject the users “first_name” and “favorite_color” back into the original HTML form. Does this make sense?
The database I created for this help post, looks like this:
database image
When a user wishes to edit their data, they can enter their "first_name", in a form text input, (im assuming?) where their "first_name" will be found in the data base. The ouutput result of this database query will be injected into the original form, ready for any user edit.
User Edit for: Results (in origingal form):
Jack Jack Black
Jeff Jeff Green
Randall Randall Red
So on.........
I hope this explanation makes sense where any experienced help or direction is offered.
Thanks for viewing!
just for practice purposes, but can look into prepared statements at you liesure time.
first create ur php file
<form method="post" action="edit.php">
<?php
//in ur php tag. select items from the row based on an id you've passed on to the page
$sql = "select * from 'form_data' where blah = '$blah'";
$result = mysqli_query($connection, $sql);
if($result){
$count = mysqli_num_rows($result);
if($count > 0) {
while($row = mysqli_fetch_assoc($result)){
$name = $row['firstname'];
$lname = $row['lastname'];
//you can now echo ur input fields with the values set in
echo'
<input type="text" value="'.$name.'" >
';//that how you set the values
}
}
}
?>
</form>
Finally you can run and update statement on submit of this you dynamically generated form input.
Also please switch to mysqli or pdo, alot better that the deprecated mysql.
look into prepared statements too. Hope this nifty example guides you down the right path...

php select to get a variable and then apply if else on it

I have a car rental system I am working on. When a user rents a car, the system should first check if the number of available cars is greater than 0, if yes, then make the adjustment "AVAILABLE = AVAILABLE+1" (in the MySQL table which keeps track of cars), which means, rent the car to the user. Also, I am trying to record which car went to which user. So I have another database table called rentalrecords which takes in the values of the Username of the logged in user, and ID of the car rented. Now, the problem is, my 'IF-ELSE' part is not executing as desired.
<div id="stylized" class="myform">
<form id="form" name="form" method="POST" action="renting.php" >
<h1>Rent a Car</h1>
<label>Car ID
<span class="small">eg. Enter 1 for Mer1</span>
</label>
<input type="text" name="ID" id="ID" />
<input type="submit" style="margin:30px 100px;" name="submit" value="Check-Out">
<div class="spacer"></div>
</form>
</div>
Now,the action of this form, which is renting.php, is as follows:
<?php
session_start();
if(!session_is_registered(theUSERNAME)){
header("location:customer_login.php");
}
mysql_CONNECT("xx", "xx", "xx") OR DIE("Unable to connect");
mysql_SELECT_DB("xx") OR DIE("Unable to select database");
$ID = $_POST['ID'];
$result = mysql_query("SELECT AVAILABLE FROM car WHERE ID='$ID'");
if(mysql_fetch_array($result)>0)
{
$query="UPDATE car SET AVAILABLE=AVAILABLE-1 WHERE ID='$ID'";
mysql_query($query);
$query = "insert into rentalrecords (USERNAME,ID,RENTED_ON) values ('$_SESSION[theUSERNAME]','$_POST[ID]',CURDATE())";
$result = mysql_query($query);
header("location: list_Clogged.php");
}
else
{
echo "<script>alert('The car you chose is currently unavailable!'); location.href='rent.php';</script>";
}
?>
Even though I have available=0, it still is NOT executing the else part and no matter what, it always executes the IF part. The ID and AVAILABLE are the attributes of my MySQL table called 'car' and the in rental records table i just want to insert these values. I am aware that the script is vulnerable to injection at the moment, but first I want to get things working! Any immediate help would be much appreciated.
You're trying to count a resource...
if(mysql_fetch_array($result)>0)
You need to obtain the results and then count an item within those results:
$res = mysql_fetch_assoc($result);
if($res[0]['AVAILABLE'] > 0)
Note $res[0] means first row of the results. You can also use mysql_fetch_row to obtain a single result.
Keep in mind, mysql_ functions shouldn't be used at all. Look into switching to mysqli or PDO.
Also, you need to sanitize input. You're just blindly accepting $_POST['ID']
The mysql_fetch_array function doesn't do what you think it does; it returns an array, not a single value.

Categories