PHP - Getting a string from MySQL Query - php

I need to retrieve a string from a query and then use that later on in another SQL query.
This is what I have, I'm retrieving the current branch ID for the currently logged in user:
$neededBranch = mysqli_query($con, "SELECT BranchNumber FROM Staff WHERE staffID = '".$_SESSION['username_login']."'");
And then I need to use said string here like this:
$result = mysqli_query($con, "INSERT INTO SomeTable (
blah,
blah,
)
VALUES ('".$SomeValue."',"
. " '".$_SESSION['username_login']."',"
. " '".$neededBranch."')");
Now, the ". " '".$neededBranch."')");" does not work because it is expecting a string.
My question is: How do I actually get the value I'm needing from the first query and use it in the second query? I'm new at PHP and don't have a clue.

Fetch the data you queried:
$result= mysqli_query($con, $query);//query is the select stmt
$row = mysqli_fetch_assoc($result);
$neededBranch = $row['BranchNumber'];

Related

Problems using a PHP string variable in a MySQL select query

I've found many similar questions regarding this but anything I try won't work.
I'm trying to run a MySQL query using the variable $epost. When I echo this variable it displays correctly, but the query returns nothing. Entering a fixed value for $epost like:
$epost='email#email.com'
Returns the correct query from the database.
$epost=mysqli_real_escape_string($conn,$_POST['email']);
echo $epost;
$sql = "SELECT memberID FROM Member WHERE email = '$epost' limit 1";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($result);
echo $row["memberID"];

PHP error get value from database

I have php script like this
$query = "select * where userid = 'agusza' ";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)) {
echo $result;
}
when I execute, the result like this
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where userid = 'agusza'' at line 1
But when I run that sql in sqlserver, it running well
Anybody has solution ?
$query = "select * from table_name where userid = 'agusza' ";
See the corrections I have made. You haven't used the right syntax for SELECT query
You didn't select a table using FROM. Without that, it does not know which table you are selecting data from.
You should also stop using mysql as it is deprecated. Use mysqli or PDO as they are safer.
You are also echoing the wrong variable in your while loop, try this:
while ($row = mysql_fetch_array($result) {
echo $row['column_name'];
}
$query = "select * from table where userid = 'agusza'";
Right now, you're not telling which table SQL should look in.
You should format your query like so:
select * from `TableName` where userid='agusza'
In your query below you doesnt state the database table where you should get that data using FROM
$query = "select * where userid = 'agusza' "; // instead of this
$query = "select * FROM declaredtable where userid = 'agusza' "; used this

show row data from a specific ID

I'm building a simple bug tracking tool.
You can create new projects, when you create a project you have to fill in a form, that form posts to project.class.php (which is this code)
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_real_escape_string($sql);
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php?id='.mysql_insert_id());
}
else {
echo "There is something wrong. Try again later.";
}
mysql_close();
(It's not yet sql injection prove, far from complete...)
Eventually you get redirected to the unique project page, which is linked to the id that is stored in the MySQL db. I want to show the name of that project on the page, but it always shows the name of the first project in the database.
(here I select the data from the MySQL db.)
$query = 'SELECT CONCAT(name)
AS name FROM projects';
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
(here I show the name of the project on my page, but it's always the name of the first project in the MySQL db)
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
How can I show the name of the right project? The one that is linked with the id?
Do I have the use WHERE .... ?
Yes, You have to use the WHERE to specify which project You want to get. I'm also not sure why are You using CONCAT function when You want to get only one project.
Other important thing is that You have to use mysql_real_escape_string() function on parameters before You put them in the query string. And use apropriate functions for specific type of data You receive.
So Your statement for getting the project should look like this:
SELECT name FROM projects WHERE id = ' . intval($_GET['id'])
Also when before You use the mysql_fetch_assoc() function, check if there are any records in the result with
if(mysql_num_rows($result) > 0)
{
$project = mysql_fetch_assoc($result);
/* $project['name'] */
}
try this
// first get the id, if from the url use $_GET['id']
$id = "2";
$query = "SELECT `name` FROM `projects` WHERE `id`='".intval($id). "'";
$result = mysql_query(mysql_real_escape_string($query));
use mysql_fetch_row, here you'll not have to loop through each record, just returns single row
// if you want to fetch single record from db
// then use mysql_fetch_row()
$row = mysql_fetch_row($result);
if($row) {
echo '<h5>'.$row[0].'</h5>';
}
$row[0] indicates the first field mentioned in your select query, here its name
The might be of assistance:
Your are currently assing a query string parameter projectpage.php?id=
When you access the page the sql must pick up and filter on the query string parameter like this:
$query = 'SELECT CONCAT(name) AS name FROM projects WHERE projectid ='. $_GET["id"];
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
Also maybe move mysql_insert_id() to right after assigning the result just to be safe.
$result = mysql_query($sql);
$insertId = mysql_insert_id();
Then when you assign it to the querystring just use the parameter and also the
header('Location: ../projectpage.php?id='.$insertId);

PHP Query failing, show error?

I have a query on my page that uses a GET variable to pull data from my table...
If I echo my GET var the data is there so im doing something wrong with my query, instead of or die can I show an error in the browser?
// Get USER ID of person
$userID = $_GET['userID'];
// Get persons
$sql = 'SELECT * FROM persons WHERE id = $userID';
$q = $conn->query($sql) or die('failed!');
$sql = "SELECT * FROM persons WHERE id = $userID";
You must use double quotes to use variables inside the query string.
You can also do this:
$sql = "SELECT * FROM persons WHERE id = ".$userID;
What you should do is this (to protect yourself from sql injection):
$safeuid = $conn->prepare($userID);
$sql = "SELECT * FROM persons WHERE id = ".$safeuid;
You can always debug using this at the top of your php page:
ini_set('display_errors',1);
error_reporting(E_ALL);
Have you tried $q = $conn->query($sql) or die($conn->error()); ?
Yes you can, but you should only do it for debugging. Crackers can gain a lot of insight by purposefully feeding bad input and reading the error.
I'm assuming you're using MySQLi; the command is $conn->error(). So your line would be:
$q = $conn->query($sql) or die($conn->error());
Also, what you're doing wrong is you're using single quotes to define $sql. You need to use double quotes to write $userID into the string. So what you want is:
$sql = "SELECT * FROM persons WHERE id = $userID";
or
$sql = 'SELECT * FROM persons WHERE id = ' . $userID;
You need to use double quotes to evaluate variables within the string. That is,
$sql = 'SELECT * FROM persons WHERE id = $userID';
should be
$sql = "SELECT * FROM persons WHERE id = $userID";
Rather than removing the die you should make sure the query is always valid. In other words: validate the userID parameter. $_GET can contain anything the user wants to provide - it could be an array, it could be a string, it could be a string with a malicious payload that can drop your tables. So check it is an integer. If not, return a relevant message to the user.
Not a php expert but you might try:
// Get USER ID of person
$userID = $_GET['userID'];
// Get persons
$sql = 'SELECT * FROM persons WHERE id = $userID';
$q = $conn->query($sql) or die('failed!' . mysql_error());
The error should append to the end of your die message.

MySQL Query using $_GET

Ok, maybe I'm a bit overtired, but I can't understand why this isn't working! I have a comments box on my website, with profiles for people who post. I want to show just their posts in the profile. Their profile page is userinfo.php?user=(whatever)
This query is failing:
$query = "SELECT message,`date`,ip,name,website,id
FROM `guestbook_message`
WHERE name=" . intval($_GET['user']) . "
AND deleted=0
ORDER BY `date` DESC";
You are getting the name of the user and casting it directly to integer and then comparing it with name. This does not make sense.
If the $_GET['user'] is the ID of the user, then compare it with the ID and not with the name.
If $_GET['user'] is the username of the user, then you have to put the quotes around the username value. As UserName value is a string, you need to encapsulate it in quotes and remove the intval. Do it like this:
$query = "SELECT message,`date`,ip,name,website,id
FROM `guestbook_message`
WHERE name='" . mysql_real_escape_string($_GET['user']) . "'
AND deleted=0
ORDER BY `date` DESC";
try this:
$name = intval($_GET['user']);
$query = "SELECT message,date,ip,name,website,id
FROM guestbook_message
WHERE name='" .$name. "'
AND deleted=0
ORDER BY date DESC";
$result = mysql_query($query) or die(mysql_error());
Assuming you're using mysql_query() to execute the query, have you checked if the query succeeded?
$query = "SELECT ...";
$result = mysql_query($query) or die(mysql_error());
Doing this will force the script to abort if the query fails and tell you why the query failed.
One thing to note that using $_GET directly in your query leaves you open to SQL injection attacks.
Consider cleaning your input prior to building your SQL statement, or use PDO / Prepared statements.

Categories