When I add this code to my Php file
include "sql_connect.php";
$query_blog="SELECT * FROM messages";
$result_blog=mysql_query($query_blog);
$num_blog=mysql_numrows($result_blog);
mysql_close();
$sql_index_menu="0";
while ($sql_index_menu < $num) {
$msg_subject=mysql_result($result,$sql_index_menu,"subject");
$msg_id=mysql_result($result,$sql_index_menu,"id");
$msg_from=mysql_result($result,$sql_index_menu,"from");
$msg_to=mysql_result($result,$sql_index_menu,"recipient");
$msg_text=mysql_result($result,$sql_index_menu,"text");
$msg_time=mysql_result($result,$sql_index_menu,"time");
$msg_read=mysql_result($result,$sql_index_menu,"readed");
?>
<tr>
<td><?php if($msg_read == "0") {echo "<img src='/images/message.gif' width='32' height='32'>";} else {echo "<img src='/images/message.png' width='32' height='32'>";}?> <?php echo $msg_time; ?></td><td><?php echo $msg_subject; ?></td><td><?php echo $msg_from; ?></td>
</tr>
<?php
$sql_index_menu++;
}
everything work BUT, when i add this to $query_blog
$query_blog="SELECT * FROM messages WHERE recipent='$username'";
so it won't work..
I tryed to change $username with my name but it still not working.
This code is working, so I copyed it and still nothing...
include "sql_connect.php";
$query="UPDATE messages
SET readed='1'
WHERE id='$id'";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
include "sql_connect.php";
$query_blog="SELECT * FROM messages WHERE id='$id'";
$result_blog=mysql_query($query_blog);
$num_blog=mysql_numrows($result_blog);
mysql_close();
$msg_text=mysql_result($result_blog,$sql_index_blog,"text");
$msg_from=mysql_result($result_blog,$sql_index_blog,"from");
$msg_subject=mysql_result($result_blog,$sql_index_blog,"subject");
$msg_time=mysql_result($result_blog,$sql_index_blog,"time");
Can you help me?
I disabled login required to page so now you can see the page (sorry for language :D) As you can see, no error
The website
as mentioned there is a typo, you misstyped recipient, anyway - i recommend you to use mysql_error() function to debug you'r code, an example would be:
$result=mysql_query($query) or die("<b>error:</b>".mysql_error()."line:".__LINE__);
The easiest way to debug a code in PHP is using echo or print_r.
In this case, you can include echo on $query_blog after setting it and run the result in your mysql IDE (or mysql command line).
$query_blog="SELECT * FROM messages WHERE recipent='$username'";
echo $query_blog;
Also, it's not a good msyql practice using quotes on where because your code will be vulnerable to injections.
Instead, use this:
$result = sprintf("SELECT * FROM messages WHERE recipent='%s'", mysql_real_escape_string($username));
$result = mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $result
die($message);
}
If you are querying a mysql database from php and you want to use php variables in your query you have to escape them, otherwise you are passing the string '$username', not the value that is stored in $username.
Does this work for you?
$query_blog="SELECT * FROM messages WHERE recipent='" . $username . "'";
var_dump($query_blog);
Related
I'm fairly new to PHP, but here is my issue, I am trying to get the results from a SQL query to display on the page, but I'm not getting anything returned.
Here is the code that I'm currently working with:
<?php
$con = mysqli_connect("localhost","user","password","database");
if (mysqli_connect_errno()) {
echo "Connect failed: ". mysqli_connect_error();
}
$de= $con->real_escape_string($_GET["decode"]);
$sql = "select * from FG99_URL where short='".$de."'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)) {
echo "url: " . $row["url"]. " - fb_url: " . $row["fb_url"]."<br>";
$url=$row['url'];
$fb_url=$row['fb_url'];
$fb_type=$row['fb_type'];
$fb_title=$row['fb_title'];
$fb_description=$row['fb_description'];
$fb_image=$row['fb_image'];
$petpro=$row['petpro'];
echo $fb_url.'test 1</br>';
echo $row['fb_url'] . "test 2</br>";
print $fb_url."test 3</br>";
print $row['fb_url']."test 4</br>";
}
?>
<head>...
This is what I get returned:
url: - fb_url:
test 1
test 2
test 3
test 4
Any help would be appriciated.
Do a var_dump($row) and see what is in the row variable.
That will help to see whether you have those data in those returning data set.
Based on the output, you are getting some data and returning data might not have the columns you are looking for.
Hope it helps.
Check your database first.
After set sql query, try this code:
$sql = "select * from FG99_URL where short='".$de."'";
echo $sql;
Copy and paste sql query into DB client like mysqladmin.
I'm in the process of making a web page that's meant to display data that's within a database. The database is stored in MySQL and I'm making the web page in PHP. The PHP code that I have is
<form action="list_projects.php" method="post">
<p>Choose Search Type: <br /></p>
<select name="searchtype">
<option value="partNo">Part Number</option>
<option value="pname">Part Name</option>
<option value="color">Part Colour</option>
<option value="weight">Part Weight</option>
<option value="city">City</option>
</select>
<br />
<p>Enter Search Term: </p>
<br />
<input name="searchterm" type="text" size="20"/>
<br />
<input type="submit" name="submit" value="Search"/>
</form>
<?php
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'No search details. Go back and try again.';
exit;
}
$query = "select * from project where ".$searchtype." like '%".$searchterm."%'";
var_dump($query);
$result = mysqli_query($link,$query);
$num_results = mysqli_num_rows($result);
echo "<p>Number of projects found: ".$num_results."</p>";
for ($i=0; $i <$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<p><strong>".($i+1).". Part Number: ";
echo htmlspecialchars(stripslashes($row['partNo']));
echo "</strong><br />Part Name: ";
echo stripslashes($row['pname']);
echo "<br />Part Colour: ";
echo stripslashes($row['color']);
echo "<br />Part Weight: ";
echo stripslashes($row['weight']);
echo "<br />City";
echo stripcslashes($row['city']);
echo "</p>";
}
mysqli_free_result($result);
mysqli_close($link);
?>
but when I run it, I get string(49) "select * from project where projectNo like '%J1%'" Number of projects found: This PHP script is meant to load different projects that's within the database and in a welcome.php script that calls this script connects to the database and it does connect to it correctly.
Looks like you've var dumped the wrong variable. You could try this instead:
$query = "SELECT * FROM project WHERE ".$searchtype." LIKE '%".$searchterm."%'";
$result = mysqli_query($link,$query) or die("Line ".__LINE__." Error found: ".mysqli_error($link)); // If there's an error, it should show here.
Because it's painful, I want to rewrite your code and show you how you should be doing this:
Please note that at the top of your page is a reference to an include file in which you would set your database variable ($link).
<?php
//include "../../reference/to/mysql/login.php";
/***
* The below code block should be in your include file referenced above
***/
$link = mysqli_connect("localhost", "my_user", "my_password", "my_db");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
/***
* End connection block
***/
/***
* Your data is POSTed so it can not be trusted and must at the
* very least be escaped using the below functions.
***/
$searchtype=mysqli_real_escape_String($link,$_POST['searchtype']);
$searchterm=mysqli_real_escape_String($link,$_POST['searchterm']);
$searchterm=trim($searchterm);
/***
* Because your $searchtype is a column reference you need to ensure
* it fits the allowed characters criteria for MySQL columns
***/
$searchtype = preg_replace("/[a-z0-9_]/i","",$searchtype);
Please read the MySQL manual about the allowed characters to use in column names. $ is also allowed but I'm removing that from here because you really should not be using that symbol as a column name character.
if (!$searchtype || !$searchterm) {
echo 'No search details. Go back and try again.';
exit;
}
$query = "select * FROM project WHERE ".$searchtype." LIKE '%".$searchterm."%'";
$result = mysqli_query($link,$query) or die("Line ".__LINE__." Error: ".mysqli_error($link));
$num_results = mysqli_num_rows($result);
echo "<p>Number of projects found: ".$num_results."</p>";
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$i++;
echo "<p><strong>".$i.". Part Number: ";
echo htmlspecialchars($row['partNo']);
echo "</strong><br />Part Name: ";
echo htmlspecialchars($row['pname']);
echo "<br />Part Colour: ";
echo htmlspecialchars($row['color']);
echo "<br />Part Weight: ";
echo htmlspecialchars($row['weight']);
echo "<br />City ";
echo htmlspecialchars($row['city']);
echo "</p>";
}
?>
Hopefully you can see here that I have replaced your for loop with a while loop that does the same thing, taking each row from the database one at a time and outputting it as an array with identifier $row .
I have also used mysqli_fetch_array instead of your fetch_assoc.
I have corrected the spelling mistake in your stripslashes function, but also replaced stripslashes with htmlspecialchars because stripslashes is an old and almost useless renegade function that should not be used with even remotely modern Database interfacing
Your issue is also that this page coded here has not had $link declared for it, the $link idenitifier needs to be set at the top of every page that wants to connect to the database. You need to remember that PHP does not remember standard variables across pages so just because you setup $link in welcome.php does NOT mean that it is known in this page here.
Use or die (mysqli_error($link)); appended to the end of your queries to feedback to you what errors occur.
You must also get into the habit of using PHP Error Reporting to make any headway in solving your own issues.
$link is usually set up in a PHP include file that you simply call at the top of every PHP page that requires it.
IF needed, details about how to connect to MySQLi.
Current code:
<?php
session_start();
if ($_SESSION['username']) {
echo "Signed in as " . "$_SESSION[username]" . "<br />" . "<a href='logout.php'>Log out</a>";
//Get user info.
$results = mysql_query("SELECT * FROM users WHERE username=$_SESSION[username]");
while($row = mysql_fetch_array($results) {
$db_username = $row['username'];
echo $db_username;
}
}
else {
echo "Log in";
}
?>
Unfortunately I'm getting errors when returning the values that MySQL is supposed to be getting. Any idea why?
You forgot to use single quote around value in query
mysql_query("SELECT * FROM users WHERE username='{$_SESSION[username]}'");
^^ ^^
Also stop using mysql_* functions they are deprecated, Use MySQLi OR PDO.
Your query is wrong since it contains PHP variables not enclosed in single quotes or curly braces.
You can rewrite the query as follows:
With braces:
$results = mysql_query("SELECT * FROM users WHERE username={$_SESSION[username]}");`
Or with single quotes:
$results = mysql_query("SELECT * FROM users WHERE username='$_SESSION[username]'");
I've got a php file fetching some data from a MYSQL database. This is my code so far:
<?php
include 'DB.php';
$connection=mysql_connect(DB_SERVER,DB_USER,PASS);
$db=mysql_select_db(DB_Name);
$sql="select * from lookup where id = ".$_GET['id'];
$res=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($res))
{
echo $row['message'];
}
?>
What would I have to add so that if there was no data, there'd be an error message? I'm guessing an If/else statement but I'm not sure how to fit it in with the while syntax.. any help?
$res = mysql_query(...) ...;
if (mysql_num_rows($res) == 0) {
die("Hey, nothing here!");
}
Beyond that:
a) you're utterly vulnerable to SQL injection attacks. Stop your coding project and learn about them before you go any further.
b) stop using the mysql_*() functions. They're deprecated.
You can use $count = mysql_num_rows($res); to get the number of rows returend. Then you can use an if statement to display whatever error.
I did it like mentioned above:
$query = "select * from lookup where id = ".$_GET['id'];
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$num_results = mysql_num_rows($result);
if ($num_results == 0){
echo "nothing here</br>";
}
else{
echo "<b> $num_results </b> result(s) match your query</br>";
while($row=mysql_fetch_array($res))
{
echo $row['message'];
}
You can of course leave the "echo $num_results..." out, but there you can give the number of results, which is sometimes quite useful.
HI Guys,
I have following problem. I'm trying to connect from my Iphone app to a php site, to access the mySql db, to get the right information.
This is my code:
<?php
mysql_connect ("localhost", "user", "pass") or die (mysql_error());
echo "Connected to MySql <br /><hr />";
mysql_select_db ("database_com") or die (mysql_error());
echo "Connectted to Database <br /><hr />";
$country = $_POST['country'];// THIS IS THE VALUE I WANT TO LOAD INTO THE SELECT STATEMENT
echo "value <br /><hr />" . $country;
$query = "SELECT * FROM world WHERE land='$country'";
$result = mysql_query($query) or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
$1 = $row['1'];
$2 = $row['2'];
$3 = $row['a3'];
$4 = $row['4'];
$xmltext = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<country></country>";
$xmlobj = simplexml_load_string($xmltext);
$xmlobj->addChild("1", $1);
$xmlobj->addChild("2", $2);
$xmlobj->addChild("a3", $a3);
$xmlobj->addChild("4", $4);
print header("Content-type: text/plain") . $xmlobj->asXML(); // Place future code ABOVE this line
$xml->save(statistic.xml);
}
?>
If I hardcode the value of land = "Germany" i get an answer, but if I do the other thing, nothing comes out of it.
I hope u can help me.
Do you have a form that posts a country to your php page? If so, is the form using method="post"? If you are sticking the country in the url, use $_GET instead of $_POST.
Also, call mysql_real_escape_string($_POST['country']) to avoid SQL injection issues (like someone deleting all your databases).
Also, this line:
print header("Content-type: text/plain") . $xmlobj->asXML();
has a number of issues. It should be:
header("Content-type: text/plain");
print $xmlobj->asXML();
However, you cannot send headers after printing other stuff out - like your echo calls early in the script. It doesn't sound like this is a problem yet, but it will be when your query works.
Also, you're looping through the result set. If you expect only one result, ditch the while loop. If you have more than one result, you will get errors because of the header() call.
What happens if you print_r or var_dump($_POST)? At first glance, it looks like your POST is empty, or at least $_POST['country'].
Have you check the $_POST['country'] actually contains a value?
Try
echo $query;
and update the post so we can see the content.
Try a simple error catch:
<?php
mysql_connect ("localhost", "user", "pass") or die (mysql_error());
echo "Connected to MySql <br /><hr />";
mysql_select_db ("database_com") or die (mysql_error());
echo "Connectted to Database <br /><hr />";
$country = $_POST['country'];// THIS IS THE VALUE I WANT TO LOAD INTO THE SELECT STATEMENT
echo "value <br /><hr />" . $country;
if (!isset($country) || $country == FALSE /* other fail conditions */) {
echo "<p>There was a problem; one, or more, error condition occurred:</p>";
echo "<pre>" . print_r(get_defined_vars(),true) . "</pre>";
}
else {
// database access stuff
}
?>
This way, if the values aren't set (or error-tests are met) you get a display of all the variables currently defined and the database access doesn't occur.
It's crude, but it sometimes helps to see what's happening. Though, personally, I think it far more likely that you're simply experiencing a typo $_POST['country'] instead of $_POST['contry'] or something, or using $_POST instead of $_GET.
A good way to debug this is to put this block at the top of your file:
<?php
if (!isset($_POST)) {
die('A $_POST is required for this page.');
}
...
writing this peace of code can debug your program
<?php
if (!isset($_POST)) {
}
?>
If
$country = $_POST['country'];
is returning proper value than you just need to change
$query = "SELECT * FROM world WHERE land='$country'";
as
$query = "SELECT * FROM world WHERE land='".$country."'";
otherwise just check if you are receiving $_POST['country'] values properly if not then debug it first.