load table data from mysql into one input field - php

I'm working on trying to input data from mysql into one field, below is mysql code: what I'm trying to do is have all the data from $row['db_numbers']; load into the
<input type="text" name="db_numbers" values="<?php echo $row['db_numbers'];?>
but it makes double the fields
were i end up with multiple db_number fields, I only want one.
<?php
$query = "SELECT * FROM sms_numbers WHERE `db_user` ='".$user_name."'";
$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query."<br />Error: (".mysql_errno().") ".mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$group_sms = $row['db_numbers'];
}
?>

Try this:
<?php
$query = "SELECT * FROM sms_numbers WHERE `db_user` ='".$user_name."'";
$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query."<br />Error: (".mysql_errno().") ".mysql_error());
WHILE($row = mysql_fetch_assoc($result)) {
$group_sms .= $row['db_numbers'];
}
?>
And then:
<input type="text" name="db_numbers" values="<?php echo $group_sms;?>">
Notice the '.=' in the while loop. It concatenates the numbers. Maybe add some spaces between them if you want ('. " "')?
WHILE($row = mysql_fetch_assoc($result)) {
$group_sms .= $row['db_numbers'] . " ";
}
Then echo the $group_sms variable since that contains all the db_numbers.
Hope that helps.

I think, if you are directly returning $row['db_numbers'] after querying the DB, then you can just print the $group_sms in the <input /> tag.
So my opinion would be:
- either return $row after querying the DB
- or directly use $group_sms in <input /> tag

If you're just trying to create an input element containing the value from a single field in the database there is no need for looping, use this:
<?php
$sql = "SELECT db_numbers FROM sms_numbers WHERE username = '$user_name'";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
$db_numbers = $value->id;
?>
If you have multiple values that you want to concatenate or sum you could do that directly in the query and use the same code otherwise:
$sql = "SELECT GROUP_CONCAT(db_numbers SEPARATOR '') AS db_numbers FROM sms_numbers WHERE username = '$user_name'";
$sql = "SELECT SUM(db_numbers) AS db_numbers FROM sms_numbers WHERE username = '$user_name'";
Then use this to output:
<input type="text" name="db_numbers" values="<?php echo $db_numbers;?>

Related

How to display mysql data from php in html form.(NOT TABLE)

I have been looking for a solution for this for a while but they all pertain to html tables. I have a simple form and have manually added values into the database using phpMyAdmin. I have a drop down menu at the top and whenever the admin selects a particular name from the drop down menu and presses the 'Display the fields' button, I want all the respective fields to be filled in with the values after which the admin can make changes onto any particular field and update. How can I get those values to be filled? I have tried multiple codes but keep getting errors such as undefined index, undefined variable etc. Can someone help me with that?
<!doctype html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_dealer_track";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed". $conn->connect_error);
}
if(isset($_POST['id1'])){
$sql = "SELECT * FROM tbl_dealer_info ";
$sql .= "WHERE $account_name = 'account_name' ";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)){
?>
<html>
<head>
<title>iMobile </title>
</head>
<body bgcolor = "#D6DFE3">
<center><b><h2>Please enter the following information: </h2></b></center>
<form action = "dealer_track.php" method = "post">
<strong><center> <u>Fields marked with an asterisk(*) are required.</u><br><br>
Name of the dealer:* // This is where the admin selects the user they would like to update
<?php
$sql = "SELECT account_name FROM tbl_dealer_info ";
$result = mysqli_query($conn, $sql);
echo "<select name = 'account_name' id = 'id'>";
echo "<option value = ''>";
while($row = mysqli_fetch_array($result)){
echo "<option value = '" .$row['account_name'] . "'>" . $row['account_name'] . "</option>";
}
echo "</select>";
?>
<br><br>
<input type = submit id = "id1" name = "id1" value = "Display the fields" /><br>
</center>
<hr>
<br><br>
</form>
<form action = "dealer_track.php" method = "post">
Email:*<br>
<input type = "email" name = "email" id = "id3" value = "<?php echo $row['email']?>" Required /><br><br>
RSM:*<br>
<?php
$sql = "SELECT rsm_val FROM tbl_rsm_drop_down ";
$result = mysqli_query($conn, $sql);
echo "<select name = 'rsm_val'>";
echo "<option value = ''></option>";
while($row = mysqli_fetch_array($result)){
echo "<option value = '" .$row['rsm_val'] . "'>" . $row['rsm_val'] . "</option>";
}
echo "</select>";
?>
<br><br>
**// My radio buttons aren't getting checked though**
iPhone Boost Approved:
<input type = "radio" name = "boost_app" <?php if(isset($boost_app)&& $boost_app =="Yes")?> value = "Yes" />Yes
<input type = "radio" name = "boost_app" <?php if(isset($boost_app)&& $boost_app =="No")?> value = "No" />No<br><br>
</form>
<?php
}} // While loop and if loop at the start
?>
</body>
</html>
I'm taking a wild guess here, so I'm assuming you want to select a user from a dropdown (That could be a bad idea if many people are in said database), but you would want to make a simple HTML form and name it somethign you will remember. Under the form put this?
<?php
if(isset($_POST['formnamehere'])) {
$sql = "SELECT * FROM (table name) WHERE accountname=" . $accountname;
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row['accountname'];
//put other things here, etc.
}
?>
Granted this code is not meant to be used exactly. but to give you a general idea.
You code is a bit messy but here is what you need to do generally.
First query for the unique record:
$sqlQuery = "SELECT id, firstname, lastname FROM Table Where id = '$id'";
Then run the query:
$result = $connection->query($sqlQuery ); //nb: $connection is your connection variable
Then check if any result found:
if ($result->num_rows > 0) { ........ }
If any records found then put the fetched data in variables like this
while($row = $result->fetch_assoc()) {
$firstname = $row["firstname"];
$lastname = $row["lastname"];
//and so on....
}
// You can display these variables any how you want in here, eg:
echo "<h2>$firstname</h2>";
or
<input type="text" id="firstname" name="firstname" value="<?php echo $firstname ?>" />
//nb: you must close the php tag before using html and re open it after
if "if ($result->num_rows > 0) {...} is false, just use an else {...} to display a message
You can run a query with your active connection to fetch your respective information from the table you want, along with a search clause for where the name is equal to a given value.
Query:
$result = mysqli_query($con, "SELECT `data` FROM `table` WHERE `name` = '$name';");
You can then display your data on your front end by outputting the result.
<?php
if($row = mysqli_fetch_array($result)) {
echo $row["data"];
}
?>

You have an error in your SQL syntax while doing a basic SELECT

I'm trying to search a MySQL database for the user specific website activity, to do this I created a form and process to search through a statistics table and return every record with a userID matching the query. However I keep getting this message and not sure why:
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 '#hotmail.com' at line 1
This is the form I'm using
<form method='get' action='searchuser.php' id='searchuser'>
<input type='text' input name='txtSearch' id='txtSearch'>
<input type='submit' name='submit' value='Search'>
</form>";
and this is the process file
<?php
require_once( "Functions.php" );
$header = makeHeader();
$con= connect();
$user = $_GET['txtSearch'];
$query = "SELECT * FROM statistics WHERE userID = $user";
$result=mysql_query($query) or die (mysql_error());
echo"<table border='1'><th>User</th><th>IP</th>
<th>Date</th><th>Page visited</th><th>Page from</th>";
while($row = mysql_fetch_assoc($result))
{
$username = $row['userID'];
$ip = $row['ipAddress'];
$date = $row['dateOfVisit'];
$pagev = $row['pageVisited'];
$pagef = $row['pageFrom'];
echo "<tr><td>".$row->UserID."</td><td>".$row->ipAddress."</td><td>".$row->dateOfVisit."</td><td>".
$row->pageVisited."</td><td>".$row->pageFrom . "<br/>\n"."</td></tr>";
}
IF (mysql_num_rows($queryresult) == "")
{
Echo "<p>Sorry there were no results for your search<p> <br /><br /> <p><A HREF='javascript:javascript:history.go(-1)'>Click here to go back to previous page</A></p>";
}
$footer = makeFooter();
?>
The SQL problem was with
userID = $user
The correct way of putting a string into sql query is
to delimit it with quotes
and use mysql_real_escape_string to escape possible delimiters that may happen inside.
So. the right code would be
$user = mysql_real_escape_string($user);
$query = "SELECT * FROM statistics WHERE userID = '$user'";
try this one
$user = $_GET['txtSearch'];
$query = "SELECT * FROM statistics WHERE userID = ".$user." ";
this working for me

selecting row from mysql if id matches

I want to select a row from mysql which matches a specific id. I want to get the result if the ID matches, if the ID does not exists in the database, it should not do anything.
I run sth like this:
$q = "SELECT * FROM entries where id= '1'";
$result = mysql_query($q) or die(mysql_error());
if($result){
$row = mysql_fetch_array($result) or die(mysql_error());
$name = $row['name'];
}
echo "hello".$name;
If the id '1' exists in the db, it should get the name, otherwise nothing or at least it should give the error, but when i use this, it just display no any content of the page which comes after this code. What I'm doing wrong?
If it does not display any code after this code, this is probably due to an error occuring and your error handling being set so the error is not displayed.
Try searching for the php error log file (normaly php_error.log) that should contain the error that you do not see.
Another thing i would try is adding more echo statements to see where exactly php stops interpreting.
Like this:
$q = "SELECT * FROM entries where id= '1'";
$result = mysql_query($q);
echo '<br />Query is send';
if(!$result) {
die('<br/>MySQL Error: ' . mysql_error());
}
else {
echo '<br />Result is true';
$row = mysql_fetch_array($result);
echo '<br />tryed fetching row';
if ($row === FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
die('<br/>MySQL Error: ' . mysql_error());
}
}
echo '<br />hello: "' . $name . '"';
That might help to get some more information about your problem.
$id = 1;
$sql = "SELECT `name` FROM `entries` WHERE `id` = $id LIMIT 1" //Since the id is probably an integer type on the DB, the single quotes aren't necessary, and sometimes screw it up. I think MySQL possibly thinks it's a string when in quotes.
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result))
{
$row = mysql_fetch_assoc($result) or die(mysql_error());
$name = $row['name'];
echo 'Hello ' . $name;
}
A SELECT query can return 0 rows if the condition you specified doesn't match any rows, and that isn't an error.
You should rather check the result of mysql_num_rows() after sending the query.
Maybe you should add a else statement to your if.
if($result)
....
else
do something
You might even want to do a try catch statement.

MySQL: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result
I have this bug:
mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/marlon/domains/webmasterplaats.nl/public_html/edit.php on line 36
This is the code:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$toegang[] = '86.91.195.26';
$toegang[] = '84.86.189.70';
$valid = true;
if(in_array($ip, $toegang) || isset($valid))
{
if(isset($_GET['id']))
{
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
mysql_query("UPDATE news SET titel='" . mysql_real_escape_string($_POST['titel']) . "', inhoud='" . mysql_real_escape_string($_POST['edit2']) . "' WHERE id='" . mysql_real_escape_string($_GET['id']) . "'");
echo 'Met success geupdate.' ;
}
$database = mysql_connect('localhost','marlonhe19','123456789asd');
mysql_select_db('wmp', $database);
$id = $_GET['id'];
$mysql = mysql_query("SELECT * FROM news WHERE id='$id' ;");
while($row = mysql_fetch_assoc($mysql)){
$id = $row['id'];
$titel = $row['titel'];
$inhoud = $row['inhoud'];
echo '
<form id="form1" name="form1" method="post" action="">
<input type="text" name="titel" value="$titel" /><br />
<textarea name="edit2">$inhoud</textarea> <br />
<input type="submit" name="Submit" value="Opslaan" />';
}
}
}
What's the problem?
Warning: SQL injection possible.
It looks like your query failed.
Replace this:
$mysql = mysql_query("SELECT * FROM news WHERE id='$id' ;");
With:
$mysql = mysql_query("SELECT * FROM news WHERE id='$id' ;") or die(mysql_error());
You should make your own error handling function, it's prefferable to display an error message, without exiting immediately.
You don't need a semi colon(;) in:
$mysql = mysql_query("SELECT * FROM news WHERE id='$id' ;");
Since you are passing a ;, the query execution fails and mysql_query return false and not an object. When you pass false to mysql_fetch_assoc it gives the error that you are getting.
Always add error check:
$mysql = mysql_query("SELECT * FROM news WHERE id='$id'") or die(mysql_error());
Looks like your DB selection part has a problem. Add error checking to that aswell:
EDIT:
mysql_select_db('wmp', $database) or die(mysql_error());
You should check for errors, eg.
$news_result = mysql_query("SELECT * FROM news WHERE id='$id'")
or die("Query failed: ".mysql_error());
In addition, you should name your query result variables something sensible, i.e. not $mysql and you should be using bind variables to protect against SQL injection. Consider a query string of the following:
page.php?id='+OR+'1'='1
Have you tried running the query from mysql prompt.
Looks like query returns error.
Try changing your line
$mysql = mysql_query("SELECT * FROM news WHERE id='$id' ;");
to
$mysql = mysql_query("SELECT * FROM news WHERE id='$id' ;") or die(mysql_error());

Checkboxes, SQL select statements & PHP

I am trying to display some rows from a database table based on choices submitted by the user. Here is my form code
<form action="choice.php" method="POST" >
<input type="checkbox" name="variable[]" value="Apple">Apple
<input type="checkbox" name="variable[]" value="Banana">Banana
<input type="checkbox" name="variable[]" value="Orange">Orange
<input type="checkbox" name="variable[]" value="Melon">Melon
<input type="checkbox" name="variable[]" value="Blackberry">Blackberry
From what I understand I am placing the values of these into an array called variable.
Two of my columns are called receipe name and ingredients(each field under ingredients can store a number of fruits). What I would like to do is, if a number of checkboxes are selected then the receipe name/s is displayed.
Here is my php code.
<?php
// Make a MySQL Connection
mysql_connect("localhost", "*****", "*****") or die(mysql_error());
mysql_select_db("****") or die(mysql_error());
$variable=$_POST['variable'];
foreach ($variable as $variablename)
{
echo "$variablename is checked";
}
$query = "SELECT receipename FROM fruit WHERE $variable like ingredients";
$row = mysql_fetch_assoc($result);
foreach ($_POST['variabble'] as $ingredients)
echo $row[$ingredients] . '<br/>';
?>
I am very new to php and just wish to display the data, I do not need to perform any actions on it. I have tried many select statements but I cannot get any results to display. My db connection is fine and it does print out what variables are checked.
Many thanks in advance.
EDIT:
Thanks a million for replying. However, I tried correcting my own code=blank page and both solutions above ==blank pages also. Grrrr!! Here is one solution I tried.
<?php
// Make a MySQL Connection
mysql_connect("localhost", "", "") or die(mysql_error());
mysql_select_db("") or die(mysql_error());
$query = "SELECT receipename FROM fruit ";
$cond = "";
foreach($variable as $varname)$cond .= " $varname like 'ingredients' OR";
$cond = substr_replace($cond, '', -2);
$query .= " WHERE $cond";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
echo $row['receipename'],'<br />';
}
I also tried
<?php
// Make a MySQL Connection
mysql_connect("localhost", "24056", "project99") or die(mysql_error());
mysql_select_db("24056db2") or die(mysql_error());
$variable=$_POST['variable'];
foreach ($variable as $variablename)
{
$query = "SELECT receipename FROM horse WHERE ingredients = '".$variablename."'";
while($row = mysql_fetch_assoc($query))
{
echo $row['receipename']."<br/>";
}
}
?>
I suppose another way to say it, if the checkbox variable is equal to a record under the ingredients column, I wish to print out the receipename of that record.
Im nearly getting confused here mysellf, haha.
Any other ideas I could try???
Correction in ur code
$query = "SELECT receipename FROM fruit WHERE $variable like ingredients";
$row = mysql_fetch_assoc($result);
Do u see the difference above?
Place "$query" in place of "$result" mysql_fetch_assoc($result)
My Solution
$variable=$_POST['variable'];
foreach ($variable as $variablename)
{
$query = "SELECT receipename FROM fruit WHERE ingredients = '".$variablename."'";
while($row = mysql_fetch_assoc($query))
{
echo $row['receipename']."<br/>";
}
}
Your question is not clear to me, you may try the following-
$query = "SELECT receipename FROM fruit ";
$cond = "";
foreach($variable as $varname)$cond .= " $varname like 'ingredients' OR";
$cond = substr_replace($cond, '', -2);
$query .= " WHERE $cond";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
echo $row['receipename'],'<br />';
}
NOTE: This code is not tested

Categories