I'm having trouble getting info from my MySQL database.
Here is my code :
/********************
* Database Info
********************/
$host = "localhost";
$user = "admin";
$pass = "admin#";
$database = "db_admin";
/********************
* Database connection
********************/
$con = mysqli_connect( $host, $user, $pass, $database );
if (mysqli_connect_errno ()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error ();
}
$result = array();
if (isset($_POST['ID'])) {
$id = $_POST['ID'];
$query = "SELECT * FROM Servers WHERE PID='" .$id. "'";
$result = mysqli_query($con, $query);
}
print("<pre>".print_r($result,true)."</pre>");
My first question, Did I use "isset" function currectly?
Because it doesnt seem like it is actually going though the if statement.
The Url I am using is : #..com/view.php?ID=1
My second question, Did I use the $query correctly?
Because I echo $id and that echoed out a "MySQL Object()"
Finally, the print printed out "Array()"
I'm just starting on PHP, Thanks for the help :)
A few things:
If you're passing the variable in the query string, use $_GET instead of $_POST to retrieve the values.
$result will return an pointer to the recordset, not the rows themselves. You will have to use mysqli_fetch_array() to fetch the rows.
ADD:
If you are sure that you will only have 1 record returning, you can use:
$row = mysqli_fetch_assoc($query);
echo $row['field_name'];
More then 1 record?
while($row = mysqli_fetch_assoc($query)){
echo $row['field_name'];
}
# your first question: if you have a input field with the name="ID", then its good.
Please also post your HTML :)
$var = 'Hello world';
if(isset($var)){ //If the var $var has been set (in this case it is)
echo $var;
} else {
//If $var is not set, then we get in the else
echo 'The var $var is not set';
}
The best thing is debugging the code with a debugger, you may use XDebug, or at least use var_dump(); to see what happens
var_dump($_REQUEST, $result);
Answer to your first question: It's hard to say if you've used it correctly when you haven't said what you're trying to do. I'm presuming that you only want run the code enclosed in the if-statement if the POST variable 'ID' has been received. If so, yes you've done it correctly.
Answer to your second question: I'm presuming on this line you're trying to build a string with a valid MySQL query. You've done that correctly, assuming $_POST['ID'] is a string (or can be converted to a string, see http://www.php.net/manual/en/language.types.string.php#language.types.string.casting).
If you're echoing $id and it's returning an object, however, you'll have a problem. You can't combine a string and an object like that. You'd need to iterate the object with a foreach, for example, and extract the id from that. The rest of the code won't work until that part is resolved.
The thing to investigate now is why $_POST['ID'] is returning an object. You'll need to provide the form code at the very least.
Related
So I am using this tutorial: https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/ to try and get data from my local MYSQL server (using Wamp64). I had the undefined index error at first, which I fixed using the isset() statement.
But now it just returns:
{"result":[]}
I have, however, a lot of data in the set column of that database.
Here is the code:
<?php
//Getting the requested klas
$klas = isset($_GET['klas']) ? $_GET['klas'] : '';
//Importing database
require_once('dbConnect.php');
//Creating SQL query with where clause to get a specific klas
$sql = "SELECT * FROM lessen WHERE klas='$klas'";
//Getting result
$r = mysqli_query($con,$sql);
//Pushing result to an array
$result = array();
while ($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id"=>$row['id'],
"klas"=>$row['klas'],
"dag"=>$row['dag'],
"lesuur"=>$row['lesuur'],
"les"=>$row['les'],
"lokaal"=>$row['lokaal']
));
}
//Displaying the array in JSON format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I tried out the
SELECT * FROM lessen WHERE klas='$klas'
statement in my database and it seems to return the correct data.
Any idea what is causing this?
Thanks in advance!
Point 1 is:
isset function only checks if klas is set in the $_GET global array. So if somehow $klas is blank - your query will return empty (without giving error).
So please check values in the $_GET and possibly from where it is accessed. Or you can add condition to avoid empty query like --
if (!empty($_GET['klas'])) {
// rest of the code block upto return
Point 2 is:
You have mentioned if you echo the sql it returns
SELECT * FROM lessen WHERE klas=''{"result":[]}
Here the second part (the JSON) is from echoing the result at the end of your code. So for the first part (i.e. echoing $sql) we see that klas=''. That actually goes to the Point 1 as mentioned above.
So finally you have to check why the value at $_GET is showing blank. That will solve your problem.
UPDATE:
From #GeeSplit's comment For the request
"GET /JSON-parsing/getKlas.php?=3ECA"
There will be nothing in $_GET['klas'] cause the querystring in the url doesn't contain any key.
So either you have to change the source from where the file is called. Or you can change how you are getting the value of klas.
Example:
$tmpKlas = $_SERVER['QUERY_STRING'];
$klas = ltrim($tmpKlas, '=');
Rest of your code will work.
Use this code
<?php
$klas ='';
if(isset($_GET['klas']) && !empty($_GET['klas']))
{
$klas = $_GET['klas'];
require_once('dbConnect.php');
$sql = 'SELECT * FROM lessen WHERE klas="'.$klas.'"';
$r = mysqli_query($con,$sql);
$result = array();
while ($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id"=>$row['id'],
"klas"=>$row['klas'],
"dag"=>$row['dag'],
"lesuur"=>$row['lesuur'],
"les"=>$row['les'],
"lokaal"=>$row['lokaal']
));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
}
?>
I am changing my database to add an "sex" column and after, I can't log into the my site. So I look into the get_passwd() function, and I see $passwd = $row[5] is causing the problem.
I fixed it, but is there better way to do this function, even if I adding column into the database?
function get_passwd($link, $login) {
$sql = "SELECT * FROM user WHERE email='$login'";
$result = mysql_query($sql, $link);
$row = mysql_fetch_array($result);
$passwd = $row[6];//this is the problem!
//echo $passwd;
return $passwd;
};
You're MYSQL functions are deprecated.
You should be afraid of MYSQL Injections.
... But here is a way to make the world of MYSQL safer ...
PDO - http://php.net/manual/de/book.pdo.php
Example:
$db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", "$db_user", "$db_pass");
$query = $db->prepare("SELECT username, password FROM user WHERE email = ? LIMIT 1");
// you should know which columns you are selecting
// LIMIT to make sure you don't select 2 rows.
$query->execute(array($login));
$row = $query->fetch();
echo $row["password"];
//return $row["password"];
$db = null;
Use mysql_fetch_assoc instead of mysql_fetch_array. It will return keyed array with column names as keys.
I'm guessing that everyone will tell you that it is no longer recommended to use these functions and you should switch to something like PDO, for example.
But since you might need to maintain some old application with legacy code I'm guessing that we can also stay on point and give an answer. You can use a function like mysql_fetch_assoc and the returned value will be an associative array, so you'll be able to use $row['password'] instead of $row[6]. There's also mysql_fetch_object.
Again, when you look at those manual pages please pay attention to the big notice on the red background at the top.
mysql_fetch_assoc allows you to perform a mysql query and use the response object as a key[value] array.
function get_passwd($link, $login){
$sql="SELECT * FROM user WHERE email='$login'";
$result=mysql_query($sql, $link);
$row=mysql_fetch_assoc($result);
$passwd = $row['password']; <- use the column name here
//echo $passwd;
return $passwd;
};
Find out more at the documentation page below:
http://php.net/manual/en/function.mysql-fetch-assoc.php
I am trying to retrieve a zone by running a PHP function based off of a place that has already been submitted.
Using FORM method GET, after submission, the variable that I am retrieving is:
$place = mysqli_real_escape_string($_GET['place]);
The variable immediately after is zone:
$zone = getZone($pol); // here is the PHP function call
Above both of these variables is the function getZone, which looks like this:
function getZone($place)
{
$searchZone = "SELECT ZONE FROM zones WHERE PLACE = '".$place."'";
$result = mysqli_query($dbc, $searchZone);
$row = mysqli_fetch_array($result);
return $row['ZONE'];
}
I can run the query in the database, and it returns the ZONE.
Now, the mysqli_fetch_array, which normally works for me, is failing to produce the result from the query.
Does anyone see what is wrong?
You've forgotten about PHP's variable scope rules:
$result = mysqli_query($dbc, $searchZone);
^^^^---- undefined
Since $dbc is undefined in the function, you're using a local null handle, which is invalid. If you'd had ANY kind of error handling in your code, you'd have been told about the problem.
Try
global $dbc;
$result = mysqli_query(...) or die(mysqli_error($dbc));
instead. Never assume success. Always assume failure, check for that failure, and treat success as a pleasant surprise.
This might help
//Assuming $dbc as connection variable
function getZone($dbc,$place)
{
$searchZone = "SELECT ZONE FROM zones WHERE PLACE = '".$place."'";
$result = mysqli_query($dbc, $searchZone);
$row = mysqli_fetch_array($result);
return $row['ZONE'];
}
include 'path/to/connectionfile';//Only if you haven't already done that
$zone = getZone($dbc,$pol);
Ok... I figured it out, thanks to the assistance of Marc B. I took into account that I was not providing my connection string, so I added it to the file. Problem is, I needed to add it to the actual function, like so:
function getZone($place)
{
include ("../include/database.php");
// then the rest of the code
After I included the database connection, I am now able to retrieve the zone.
Thank you.
I'm trying to create a variable which is dependent on some information from the database. I'm trying to generate a $path variable which stores a path, depending on what information is recovered from the database.
$linkid = mysql_connect('localhost','user','password');
mysql_select_db("table", $linkid);
$variable = "00001";
$groupID = null;
$temp = mysql_query("SELECT groupID FROM table WHERE memberID='$variable'", $linkid);
while ($row = mysql_fetch_row($temp)){
global $groupID;
foreach ($row as $field){
$groupID = $field;
}
}
....
$path = "C:\WAMP\www\project\\" . $groupID;
$dir_handle = #opendir($path) or die('Unable to open $path');
The idea behind this is that $variable is set before the PHP is run, however it's set to 00001 for testing. The ideal situation is that $path should equal C:\WAMP\www\project\00001\. Currently, when I echo back the $path all I get is the original path without the $groupID added to the end.
I also receive the message "mysql_fetch_row() expects parameter 1 to be resource" but I've used this method for retrieving information before and it worked just fine, and I set up my table in the same way so I don't think the issue is there.
I have a feeling I'm missing something obvious, so any help is appreciated. It's not for an assignment or anything school related (just trying stuff out to learn more) so knock yourselves out with correcting it and explaining why :)
In addition, only one memberID will ever be a match to the $variable, so if there's an alternative way to fetch it I'd appreciate knowing.
Oh, and I know my variable names are shocking but they're only that on here, on my actual code they're different so no criticism please :p
EDIT: The SQL query is correct, after following BT634's advice and when running it on phpMyAdmin I get the groupID I want and expect.
mysql_select_db("table", $linkid)
should actually be
mysql_select_db("database_name", $linkid)
since you are connecting to the database that contains the table and not the table itself.
Also, try mysql_result($temp,0) instead of the while loop
First of all, you're not specifying what database to connect to in your connection - you're specifying what table. You might also want to check how many rows your query is returning:
$temp = mysql_query("SELECT groupID FROM table WHERE memberID='$variable'", $linkid);
echo mysql_num_rows($temp);
If it's still complaining about $temp not being a valid resource, change your MySQL connection code to:
// Establish connection
$con = mysql_connect("localhost","peter","abc123");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("my_db", $con);
// Make your query
$result = mysql_query("SELECT groupID FROM table WHERE memberID='$variable'");
// Find out what the value of the query is (i.e. what object/resource it is)
var_dump($result);
Once you know that MySQL is returning valid data, extract the values you want. You don't have to use globals:
while ($row = mysql_fetch_row($temp)){
$groupId = $row[0];
}
// Use $groupId however you please...
One thing to bear in mind is that mysql_fetch_row will return
array
(
0 => '...'
)
Whilst mysql_fetch_assoc will return:
array
(
'groupId' => '...'
)
Find out what query it's definitely running, and paste that into a normal MySQL client to make sure your query is correct.
Just do this after defining "$variable"
exit("SELECT groupID FROM table WHERE memberID='$variable'");
Then copy the output into a MySQL client (or MySQL from the command line).
Try something like this:
global $groupID;
$linkid = mysql_connect('localhost','user','password');
mysql_select_db("table", $linkid);
$variable = "00001";
$groupID = null;
$sql = "SELECT groupID FROM table WHERE memberID='$variable'";
$temp = mysql_query($sql, $linkid) or die(mysql_error());
$row = mysql_fetch_row($temp);
if ($row) {
$groupID = $row['groupID'];
}
If you are retrieving a single value, and it is guaranteed to be unique, then the loop structures are unnecessary. I've added a check to ensure the query exits with an error if there's a problem - it is ideal to do this everywhere, so for example do it with mysql_select_db too.
I have a php variable: $foo
My MySQL table called data has the following structure:
id var header
1 zj3 http://google.com
I would like to check if $foo is all ready in var row.
If it is I would like to echo header ("http://google.com")
How would you approach this?
Thanks in advance, please ask if any clarification is needed!
Your query should be:
SELECT `header` FROM `data` WHERE `var` = '$foo'
This will return all the headers with a var value of $foo.
$db = mysqli_connect('localhost', 'username', 'password', 'database');
if($query = mysqli_query($db, "SELECT `header` FROM `data` WHERE `var` = '$foo'")){
while($row = mysqli_fetch_assoc($query)){
echo $row['header'];
}
mysqli_free_result($query);
}
first connect to the db
$query = mysql_query("SELECT var, header FROM data WHERE id='1'") or die(mysql_error());
while($row = mysql_fetch_assoc($query)){
if($foo == $row['var']){
echo $row['header'];
}
}
EDIT: changed equality statement based on your edit
It's not difficult at all, If I understand correctly then this should help you.
// Query Variable / Contains you database query information
$results = $query;
// Loop through like so if the results are returned as an array
foreach($results as $result)
{
if(!$result['var'])
echo $result['header'];
}
// Loop through like so if the results are returned as an object
foreach($results as $result)
{
if(!$result->var)
echo $result->header;
}
are you asking if $foo matches any of the fields in data, or if $foo=some_field? Here for if you want $foo==var.
$foo='somevalue';
$query="SELECT id, var, header FROM `data` WHERE var='$foo'";
$result=mysqli_query($query);
if($result->num_rows==0)
$loc= 'http://google.com';//default value for when there is no row that matches $foo
}else{
$row=$result->fetch_assoc(); //more than one row is useless since the first header('Location: x') command sends the browser to a new page and away from your script.
$loc=$row['header'];
}
header ("Location: $loc);
exit;
ETA: since you've edited your question, it appears that you want to echo the header column if your search value matches your var column. The above won't work for that.
You just want to know if $var's value is anywhere in that column (any row(s))?
SELECT COUNT(id) FROM data WHERE var = ?;
The result will be the number of rows for which the field var contains the value of $var.
Here's a template for all the "does it exist" questions.
This is the only thing that actually worked for me so far and is not deprecated.
if ($query = mysqli_query($link, "SELECT header FROM data WHERE var = '$foo'")) {
$header = mysqli_fetch_assoc($query);
if ($header) {
// The variable with value $foo exists.
}
else {
// The variable with value $foo doesn't exist.
}
}
else {
// The query didn't execute for some reason. (Dammit Obama!)
}
WARNING!
Even if the variable DOES NOT EXIST the comparison between $query and mysqli_query() will always return TRUE.
The only way --which happened to me-- for the comparison to return FALSE is because of a syntax error in your query.
I don't know why it worked for the guy who wrote the accepted answer, maybe it's an update or maybe he had a syntax error and was so confident that he didn't check if it could ever be TRUE.
Here's the comment someone made for correcting his syntax:
"Add another ) before the { in the first line"
So, the accepted answer is WRONG!