Query result into variable - php

I'm making a website. I want it so that I can put records into the database via my website. So first I need to select the id from which record I want to change. Then I want to put the values of the selected id into a variable. The I want to put the variable into a form value.
I'm trying to make something similar to phpmyadmin. If you click on the pencil you go to a form were everything is complete and you can just change the things you want to change and save it into the database.
wijzigen.php:
<form id="form1" name="form1" method="post" action="set_wijziging.php">
<h1>Selecteer het vuurwerkid van het product dat u wilt wijzigen</h1>
<p>Vuurwerkid <br>
<input type="text" name="vuurwerkid" id="vuurwerkid" />
<input type="submit" name="wijzigen" id="wijzigen" value="wijzigen"/>
</form>
and here is the part were I put what I typed in in the form into a variable.
<?php
$vuurwerkid=$_POST["vuurwerkid"];
?>
Then I'm trying to make a query wich only selects the things were vuurwerkid='$vuurwerkid'
So here I try to put the results of the query into a variable. But this doesn't seem to work.
set_wijziging.php:
<?php
include("connect.php");
$vuurwerkid=$_POST["vuurwerkid"];
$query = "SELECT * FROM vuurwerk_info WERE vuurwerkid='$vuurwerkid'";
$resultaat = MySQL_query($query);
while ($row = MySQL_fetch_array($resultaat))
{
$vuurwerkid="$row["vuurwerkid"]";
$naam=$row["naam"];
$prijs=$row["prijs"];
$soort=$row["soort"];
$cat_vuurwerk=$row["cat_vuurwerk"];
$aantal=$row["aantal"];
}
?>
I'm just started learning PHP

Your where spelling is wrong in your query
Try this
$query = "SELECT * FROM vuurwerk_info WHERE vuurwerkid='$vuurwerkid'";
I miss that last time Change this line as well
$vuurwerkid="$row["vuurwerkid"]";
To this
`$vuurwerkid=$row["vuurwerkid"];
//Remove the Double queite. As its variable not string`
although function name are case-incensitive. But change theese lines as well
chnage this
$resultaat = MySQL_query($query);
while ($row = MySQL_fetch_array($resultaat))
To this
$resultaat = mysql_query($query);
while ($row = mysql_fetch_array($resultaat))
Note I change nothing in the below line. I just used the small letter to right those function
Please learn MYSQLI_ OR PDO
As mysql function are depriciated.

You should change your $query to
$query = "SELECT * FROM vuurwerk_info WHERE vuurwerkid='$vuurwerkid'";
Also try to echo your query to see if it's correct.
Finally as others pointed out you should stop using mysql_* and switch to msqli or PDO.

Related

In PHP MySQL query returns EVERY row. In MySQL Workbench, it works correctly

I have a very simple PHP form:
<form action="listtenants.php" method="post">
Search for Tenant: <input name="term" type="text" value="" />
<input name="Submit" type="submit" />
</form>
At first I thought, the data was posting incorrectly; but after viewing the headers with LiveHTTP headers, it turns out it is posted correctly.
Here is my PHP script. Like I said, the query works correctly in MySQL workbench; however in the PHP script, every row is returned. Does anyone know why this could be? Even echoing the posted variable returns the expected string. Not sure what gives here.
<html>
<body>
<?php
$connect = mysql_connect("host","user","pass");
mysql_select_db("db", $connect);
$term = $_GET['term'];
$query = "SELECT itemid, first, last FROM tenants where CONCAT(first, last) LIKE '%$term%'";
$getUserid = mysql_query($query);
//$i = 0;
$records = mysql_num_rows($getUserid);
while($row_sections = mysql_fetch_array($getUserid))
{
echo "$row_sections[0] $row_sections[1] $row_sections[2]";
?>
<br><br>
<?php
}
?>
</body>
</html>
This is a terrible query and highly dangerous. BUT.. ..your issue is simple.
Your form submits via _POST, and your looking for variables using _GET.
$term = $_GET['term'];
will always be empty, so your query matches on '%%' - ie: everything!
Change it to:
$term = $_POST['term'];
..then go read about MySQL injections and follow the links in the comments to your post.

Heavy issue here trying to upload data to a database

I'm having a big issue here, I'm trying to upload some data to a database, and I really don't have a clue why it isn't getting uploaded.
This one here is my HTML form to send data to the php. (This one here should have no problem at all)
<form method="post" action="uploadinfo.php">
<div style="width:542px;height:129px;margin-left:45px;margin-top:102px">
<textarea name="stufftoupload" placeholder="Write your stuff here" rows="8" cols="65"></textarea>
</div>
<div style="width:95px;height:29px;margin-left:489px;margin-top:22px">
<input type="image" src="myimg.png">
</div>
</form>
And this one here is my PHP to upload to the database, this is where the problem should be, but I have no clue what it is. I've tried several solutions, but nothing is working.
<?php
session_start();
$db = mysql_connect("host","db","pass");
if(!$db) die("Error");
mysql_select_db("table",$db);
$email = $_SESSION['email'];
$stuff = $_POST['stuff'];
if (!$stuff)
{
echo "<script type='text/javascript'>window.alert('Fill all the blanks.')</script>";
$url = 'upload.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
}
else
{
$url = 'success.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
}
mysql_query('SET NAMES utf8');
$sql = "SELECT * FROM table WHERE email = '$email'";
$result = mysqli_query($db,$sql);
mysqli_fetch_all($result,MYSQLI_ASSOC);
$sql = "INSERT INTO table SET stuff = '$stuff'" or die(mysql_error());
$result = mysql_query($sql);
?>
So this is about it, I'm almost positive it's something within this code, but it could be some bad session managing, though I'm not totally sure about it.
Anyway, thanks in advance for the help. It'll be totally appreciated.
$db is connecting to the database using the mysql method, but you are querying based on the mysqli methods. There are 2 things you need to do here to have an idea of what is going on. Firstly, change all your mysql_ calls to mysqli_ calls, and add some error reporting (so for example adding or die (mysqli_error($db); to the end of every line where you query) should point you in the right direction.
Your first glaring problem here is that you conneced to the DB using mysql_connect, but are then trying to query that connection using mysqli. Use one, not both.
Also, your SQL Query should read INSERT INTO table (stuff) VALUES ($stuff) rather than INSERT INTO table SET stuff = '$stuff'
There are a few problems here so I'll start with what I see now.
This line:
$db = mysql_connect("host","db","pass");
is what connects to your database and I'm assuming that "host" doesn't point to anything. Depending on where that is running, normally Localhost is used. You would also need to make sure the password is correct.
As suggested, use mysqli.
Your insert needs to be something like:
INSERT INTO table VALUES ({$stuff});
Not sure what you want from that form but your session variables will have to match the input names you use on the form.
$stuff = $_POST['stufftoupload'];

PHP form search for MySQL DB

I need some help getting a search function to work. I have previously coded something to work similar to this, where if I click on a hyperlink, I'm able to carry a variable forward and then assign this into an SQL script so it pulls only this one thing back from the DB. (Predefined variable, and not user input). I've tried modifying the script I've been using to allow for a form based text box to have user input which is then searched through a single database field, with a LIKE statement.
This is what I have, and it's not returning anything.
Input Form
<form class="formFormat" method="post" action="SearchResult.php">
<label class="lableInput2">Key Words</label>
<input type="text" class="textInput" name="JobDetails" />
<input type="image" src="img/blue/buttonsearch.jpg" value="search" class="buttonInput" alt="Submit Form" border="0" />
</form>
Returning Page
<?php
include('conn_mysql.inc');
include('corefuncs.php');
// create database connection
$conn = dbConnect('query');
// initialize flag
$deleted = false;
// get details of selected record
if ($_GET && !$_POST) {
// check that primary key is numeric
if (isset($_GET['JobDetails']) && is_numeric($_GET['JobDetails'])) {
$JobDetails = $_POST['JobDetails'];
}
else {
$JobDetails = NULL;
}
if ($JobDetails) {
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%JobDetails%'";
$result = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_assoc($result);
}
}
?>
<p><h1><?php echo ($row['JobTitle'].'<span class="jobid"> #'.$row['IDJobs'].'</span>');?></h1></p>
<p><strong><?php echo ($row['Location']); ?></strong></p>
<p><strong>£<?php echo ($row['JobValue']); ?>.00</strong></p>
<p><strong>www.companyurl.com - BAD IDEA?</strong></p>
<p><strong>Open for Bidding</strong></p>
<br />
<p><span class="jobid">Job Posted: <?php echo ($row['JobPostDate']); ?></span></p>
<p><?php print ($row['JobDetails']); ?></p>
<p><span class="jobid">Job Deadline: <?php echo ($row['JobDeadline']); ?></span></p>
I know that I need to loop the output, so it displays more than one, but at the moment it simply returns the following error for every field (obv the line changes depending on what's trying to extract.
"( ! ) Notice: Undefined variable: row in
C:\wamp\www\ReEmployWork\SearchResult.php on line 54"
Can anyone assist? I'm a bit lost with this, and I believe I'm either going in the wrong direction or just missing something.
You missed $ before the variable name. Instead of:
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%JobDetails%'";
write:
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%$JobDetails%'";
You left your $ before JobDetails in you query.
Also remeber to use http://php.net/manual/en/function.mysql-real-escape-string.php
A suggestion:
$escaped_value = mysql_real_escape_string($JobDetails)
$sql = "SELECT * FROM jobs WHERE JobDetails LIKE '%$escaped_value%'";
For future readers. I scrapped the code I tried to modify and I took it from the beginning. There's enough information above for anyone to do this. Have a go, and you may end up with a result similar to what I coded.
$JobDetails = $_POST['JobDetails'];
$JobDetails = mysql_real_escape_string($JobDetails);
$sql = "SELECT * FROM `jobs` WHERE `JobDetails` LIKE '%{$JobDetails}%'";
$result = mysql_query($sql) or die (mysql_error());
?>
The above is what I coded and it runs like a dream. You make a lot more mistakes modifying code than you do, if you just code from scratch, so if you're learning dabble and play with code already wrote, but if you need something yourself which is unique then you're best starting from scratch.

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.

MySQL/PHP update query not executing

I tested the variables in the update statement and checked if a database connection is established, however the query doesn't run, can you please show me the error in my code.
for($i=0; $i <= $numcourses; $i++){
echo '<div class="new'.$i.'" id="new'.$i.'"><label>'.$course_names[$i].'</label>
<input name="edit'.$i.'" type="submit" value="Edit" /><input name="delete'.$i.'" type="submit" value="Delete" /><br /></div>';
$name="edit".$i;
if (isset($_POST[$name])){
echo '<input name="text" type="text" value="'.$course_names[$i].'" /><input name="save'.$i.'" type="submit" value="Save"/>';
}
$name2="save".$i;
if (isset($_POST[$name2])){
include "includes/open.php";
$newname=($_POST['text']);
$int=$i+1;
$query = "UPDATE course SET cname = '".$newname."' WHERE cid = '".$int."'";
mysql_query($query) or die(mysql_error());
include "includes/close.php";
}
}
Update: Thanx Marc B, adding or die(mysql_error());showed me the error in my code, everything works again and I'm back on track.
You have no error handling on your query calls:
mysql_query($query) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
which would tell you if there's any problems with the query execution. On a meta level, you're wide open to SQL injection attacks, so you'd better read up about that and fix the problem before you go any further with your code.
$query = "UPDATE course SET cname = '".$newname."' WHERE cid = '".$int."'";
is cID an integer ? in the update statement, looks to me like a string, try to echo every query and check the validity by executing it directly in your db
where do you connect to the database??
use mysql_connect(string hostname, string username, string password'); to connect to the database and then execute the query after selecting your database using mysql_select_db..
First you should remove the extra ; on $name="edit".$i;;
Then, how do you post the values? I see no <form> attributes in your code, hence it cannot be posted.
Also, everything is in a for loop. $newname=($_POST['text']); is never being set.
Maybe instead of this:
if (isset($_POST[$name2]))
try this:
if ($name2!="")

Categories