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.
Related
First I'm hitting on a wall here and I really could use your help. I coded the database so I have it all up and working plus all the data inside. I worked the HTML and the CSS media print query and I have it how I want it to look exactly. All I have to do now is:
for every row of the mysql select table I have to fill every specific input form
of the html page I made and print it
Can someone give me a hint of how I can do that?
Assuming you want to connect to your database and simply fetch the id you can do the following.
Ensure you change my_host, my_user, my-password, my_databse,my_tablewith your configuration settings. Then if you want to fetch anything else thanid` just change it to the column name you are looking for.
Be aware we are using PHP here.
// Open Connection
$con = #mysqli_connect('my_host', 'my_user', 'my-password', 'my_databse');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
// Some Query
$sql = 'SELECT * FROM my_table';
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
echo $row['id'];
}
// Close connection
mysqli_close ($con);
Check this link to get a in-depth explanation.
You can do this with two pages. One page gives you the overview and the other page gives you a print preview of your invoice.
The overview:
// DB select stuff here
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n";
echo " <td>".htmlspecialchars($row['what'])."</td>\n";
echo " <td>".htmlspecialchars($row['ever'])."</td>\n";
echo " <td>Detail</td>\n";
echo "</tr>\n";
}
The detail page:
$sql = 'SELECT your, columns FROM tab WHERE id = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo "There is no data for the given Id\n";
return;
}
echo "What: ".htmlspecialchars($row['what'])."<br />\n";
echo "Ever: ".htmlspecialchars($row['ever'])."<br />\n";
I'm working on a frequently asked questions, but for administration I want to be able to see the current frequently asked questions that have been stored in the database, and below that a form to post a new question & answer, which upon submitting will refresh the page with the new question and answer.
Here's the thing:
I've gotten it to post just fine, but I can only display the most recent one...
here's my code so far:
Getting:
<?php
//select database table
$sql = "SELECT question, answer FROM faq";
$queryresult = mysql_query($sql) or die (mysql_error());
//Request Values
while ($row = mysql_fetch_array($queryresult)){
$faqQuestion = $row['question'];
$faqAnswer = $row['answer'];
}
//echo variables
echo "<p>$faqQuestion</p>" . "<p>$faqAnswer</p>" . "<br />";
//if question and answer have null values
if ((empty($faqQuestion))&&(empty($faqAnswer))){
echo("<div><p>No Questions available</p></div>");
}
?>
<?php
mysql_free_result($queryresult);
mysql_close($conn);
?>
Posting:
<?php
include("database_conn_dcs.php");
if($_POST){
$question = ($_POST['question'])? $_POST['question']:null;
$answer = ($_POST['answer'])? $_POST['answer']:null;
$sql="INSERT INTO faq (talen_idtalen, question, answer)
VALUES ('$idtalen', '$question', '$answer')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
header("location: faq_admin.php");
}
?>
My other issue is that it also posts blank stuff. how do i prevent PHP sending null values to the database (it's already stated the variables are non-null?
Thank you so much in advance!!!
First, your echo should be in the while loop, otherwise each time it loops, your two variables are being overwritten.
Secondly, you only want to display no questions available if no results were returned, which is checked by the mysql_num_rows.
Thirdly, your input code is vulnerable to SQL Injection, which could get your website compromised. To prevent this, use prepared statements, and bind your user input ($_POST variables) instead of including them directly in the query.
<?php
//select database table
$sql = "SELECT question, answer FROM faq";
$queryresult = mysql_query($sql) or die (mysql_error());
//Request Values
while ($row = mysql_fetch_array($queryresult)){
$faqQuestion = $row['question'];
$faqAnswer = $row['answer'];
//echo variables
echo "<p>$faqQuestion</p>" . "<p>$faqAnswer</p>" . "<br />";
}
if(mysql_num_rows($queryresult) <= 0) {
echo("<div><p>No Questions available</p></div>");
}
mysql_free_result($queryresult);
mysql_close($conn);
?>
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);
I'm a PHP beginner and lately I've been having a problem with my source code.
Here it is:
<html>
<head>
<title>
Bot
</title>
<link type="text/css" rel="stylesheet" href="main.css" />
</head>
<body>
<form action="bot.php "method="post">
<lable>You:<input type="text" name="intrebare"></lable>
<input type="submit" name="introdu" value="Send">
</form>
</body>
</html>
<?php
//error_reporting(E_ALL & ~E_NOTICE);
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("robo") or die(mysql_error());
$intrebare=$_POST['intrebare'];
$query = "SELECT * FROM dialog where intrebare like '%$intrebare%'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
?>
<div id="history">
<?php
foreach($row as $rows){
echo "<b>The robot says: </b><br />";
echo $row['raspuns'];
}
?>
</div>
It returns the result 6x times.
This problem appeared when I've made that foreach because I wanted the results to stuck on the page one by one after every SQL query.
Can you please tell me what seems to be the problem? Thanks!
You are doing it wrong. ;-)
First of all you have to fetch your result with mysql_fetch_array in a loop like this:
while (true == ($row = mysql_fetch_array($result))) {
echo "<b>The robot says: </b><br />";
echo $row['raspuns'];
}
Second I want to tell you that all mysql_* functions are marked as deprecated. If you want to learn PHP you should try to learn how to connect to mysql using PDO.
mysql_fetch_array fetches one row per call. You'll want to do like this:
while ($row = mysql_fetch_array($result)) {
echo "<b>The robot says:</b><br>";
echo htmlentities($row['raspuns']);
}
and get rid of that first mysql_fetch_array.
(Notice that i am HTML-escaping the variable output. Unless you know what you're doing, you should not output raw data into a page.)
By the way, mysql_query is effectively deprecated. It is not at all recommended for new code. Take a look at mysqli (the replacement) or PDO (the new hotness). With the new mysqli (objecty) interface, the PHP part would look a bit like this:
<?php
//error_reporting(E_ALL & ~E_NOTICE);
$db = new mysqli('localhost', 'root', '', 'robo');
# turn into a wildcard
$intrebare='%' . $_POST['intrebare'] . '%';
$stmt = $db->prepare('SELECT * FROM dialog WHERE intrebare LIKE ?');
$stmt->bind_param('s', $intrebare);
$result = $stmt->execute();
echo '<div id="history">';
# 5.4 lets you do it like this;
# older versions, try `while ($row = $result->fetch_assoc())`
foreach ($result as $row) {
echo "<b>The robot says: </b><br />";
echo htmlentities($row['raspuns']);
}
?>
You're only getting one result (only one call to mysql_fetch_array()). There are six columns, I bet, in dialog.
...
$result = mysql_query($query) or die(mysql_error());
?>
<div id="history">
<?php
while($row = mysql_fetch_array($result))
{
echo "<b>The robot says: </b><br />";
echo htmlentities($row['raspuns']);
}
?>
</div>
Also, mysql_* functions are being deprecated. Switch to mysqli_* or PDO.
Use while to fetch all the data and check variable names
while($row = mysql_fetch_array($result)){
echo "<b>The robot says: </b><br />";
echo $row['raspuns']; // Here
}
You are trying it reversed way:
<?php
while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
echo '<strong>The robot says: </strong><br />', $row['raspuns'];
}
?>
Try now :)
I'm VERY new to MySQL and PHP and have been teaching myself for sometime. I'm not expecting anyone to write my code for me, but I am looking for some suggestions on how best to proceed with this script.
I have a set of users that can update their "skill level" on a particular set of products. At the moment, I have all that working. However, I don't want the user to have to update every skill level each time they submit.
So, in other words, I want them to be able to leave a field blank, but populate other fields with their skill level, thus only updating the fields they have input.
I'm doing this all on a dev server so here is my code that I'm currently working with.
mysql_connect("127.0.0.1","root","time2start") or die("Connection Failed");
mysql_select_db("joomla_dev_15") or die ("Database Connection Failed");
$user = $_POST['user'];
$USP = $_POST['USP'];
$USPV = $_POST['USPV'];
$VSP = $_POST['VSP'];
echo "$user<br />";
echo "$USP<br />";
echo "$USPV<br />";
echo "$VSP<br />";
$query = "UPDATE `joomla_dev_15`.`enterprise_storage` SET `$user` = '$USP' WHERE `enterprise_storage`.`id` = 1;";
if(mysql_query($query))
{
echo "updated<br />";
}else{
echo "FAILURE";
}
$query = "UPDATE `joomla_dev_15`.`enterprise_storage` SET `$user` = '$USPV' WHERE `enterprise_storage`.`id` =2;";
if(mysql_query($query))
{
echo "updated<br />";
}else{
echo "FAILURE";
}
$query = "UPDATE `joomla_dev_15`.`enterprise_storage` SET `$user` = '$VSP' WHERE `enterprise_storage`.`id` =3;";
if( mysql_query($query) )
{
echo "updated<br />";
}else{
echo "FAILURE";
}
Any help or suggestions would be greatly appreciated!
Maybe I'm not understanding this fully, but checking you variables before the UPDATE statement should be enough.
$user = $_POST['user'];
$USP = $_POST['USP']; // Make sure to escape this
if (!empty(trim($USP))) { // Added a trim so that when space is entered, it will still be considered empty
$query = "UPDATE `joomla_dev_15`.`enterprise_storage` SET `$user` = '$USP' WHERE `enterprise_storage`.`id` = 1;";
if(mysql_query($query))
{
echo "updated<br />";
}else{
echo "FAILURE";
}
}
else {
echo "Empty String. Nothing to Do"
}
I was able to figure it out in a way that was satisfactory for me.
Keep in mind, that this code is not necessarily sanitized or secure from malicious attacks, this is simply a dev server so I could prove the concept, and I WILL come back later and secure it.
Also, I've taught myself, so this is most likely not the most efficient way to do this
In order to get the current default values of the user's skills, I had to run this query
$result = mysql_query("SELECT id , user FROM enterprise_storage WHERE id =1");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row1 = mysql_fetch_array($result);
This allowed me to assign a variable to each row that was returned based on this specific query. So, in this case, the person (named "user" in this example) would return a skill level for Product ID "1"
Once I ran this same query for the few items I wanted to assign variables, I could then place this in my html form as the default value for each text box:
Please enter your skill level on the following products:</br>
USP: <input type="text" name="USP" value=<?php echo $row1[user]?> /><br />
USPV: <input type="text" name="USPV" value=<?php echo $row2[user]?> /><br />
VSP: <input type="text" name="VSP" value=<?php echo $row3[user]?> /><br />
I've omitted the rest of the HTML, because its not relevant right now.
In the end, this solves my problem as it places a default value into the form field, and thus the user doesn't need to update that value if they don't want to.
Thanks for all the suggestions!
Check if the form values are blank and do not post them into the database if they are - also, you really need to look at cleansing user input before putting it into the database. See http://php.net/manual/en/function.mysql-real-escape-string.php for example.