I am trying to fetch data from table. Table contains the data and query is true. Even why following query says $u and $t are not define. While condition becoming false.
I manually checked in database, it was showing results.
$url = "http://paulgraham.com/";
$user_id = "123";
$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$result = mysqli_query($con,"SELECT * FROM post_data WHERE userid =".$url." and url=".$user_id."");
while ($row = #mysqli_fetch_array($result))
{
echo "hi";
$t = $row['title'];
$u = $row['url'];
}
echo "title is : $t";
echo "url is : $u";
Giving your SQL query :
"SELECT * FROM post_data WHERE userid =".$url." and url=".$user_id.""
You can see you are mixing url and userid... Change to :
"SELECT * FROM post_data WHERE userid =".$user_id." and url=".$url.""
Also define your $t and $u variables before your loop in case you have no record.
Next time, try to var_dump your generated query to test it.
If you were able to see the errors the DBMS is reporting back to PHP then you'd probably be able to work out what's wrong with the code.
Before the 'while' loop try...
print mysql_error();
(the obvious reason it's failing is that strings mut be quoted in SQL, and you've got the parameters the wrong way around)
Related
I am trying to export my MySQL tables from my database to a JSON file, so I can list them in an array.
I can create files with this code no problem:
$sql=mysql_query("select * from food_breakfast");
while($row=mysql_fetch_assoc($sql))
{
$ID=$row['ID'];
$Consumption=$row['Consumption'];
$Subline=$row['Subline'];
$Price=$row['Price'];
$visible=$row['visible'];
$posts[] = array('ID'=> $ID, 'Consumption'=> $Consumption, 'Subline'=> $Subline, 'Price'=> $Price, 'visible'=> $visible);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
Now this reads a table and draws it's info from the fields inside it.
I would like to know if it is possible to make a JSON file with the names of the tables, so one level higher in the hierarchy.
I have part of the code:
$showtablequery = "
SHOW TABLES
FROM
[database]
LIKE
'%food_%'
";
$sql=mysql_query($showtablequery);
while($row=mysql_fetch_array($sql))
{
$tablename = $row[0];
$posts[] = array('tablename'=> $tablename);
}
$response['posts'] = $posts;
But now i am stuck in the last line where is says: $ID=$row['ID']; This relates to the info inside the Table and I do not know what to put here.
Also as you can see, I need to filter the Tables to only list the tables starting with food_ and drinks_
Any help is greatly appreciated:-)
There is no 'table id' in MySQL and therefore the result set from SHOW TABLES has no index id. The only index in the resultset is named 'Tables_in_DATABASENAME'.
Also you should use the mysqli library as the good old mysql library is depreacted. Having prepared an example:
<?php
$mysqli = new mysqli(
'yourserver',
'yourusername',
'yourpassword',
'yourdatabasename'
);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") "
. $mysqli->connect_error;
}
$result = $mysqli->query('SHOW TABLES FROM `yourdatabasename` LIKE \'%food_%\'');
if(!$result) {
die('Database error: ' . $mysqli->error);
}
$posts = array();
// use fetch_array instead of fetch_assoc as the column
while($row = $result->fetch_array()) {
$tablename = $row[0];
$posts []= array (
'tablename' => $tablename
);
}
var_dump($posts);
Connect with mysql and retrive data from the table.
my $db ="JJusers";
my $user ="root";
my $password ="abcdef";
my $host ="localhost";
my $dbh =DBI->connect("DBI:mysql:$db:$host",$user,$password);
my $uDt = $dbh->prepare("select Username,Password from Users");
my $rv = $uDt->execute;
print "<script>alert($rv)</script>";
When I execute this code I am getting the result as 1. In database the data stored as:
1, jj, pp(SNO, USERNAME,PASSWORD)
Why isn't it getting the right data?
You are printing the result of execute, not the actual database results. You want to do something like this...
while (my #data = $rv->fetchrow_array()) {
my $username = $data[0];
my $password = $data[1];
// ...
}
->execute returns just query result(0, 1, 0E0), but not resultset.
As for me, best way is:
my $res = $dbh->selectall_arrayref('select Username,Password from Users', {Slice=>{}});
# now, you can iterate result.
# for example:
foreach my $row(#$res) {
print $row->{Username};
}
If you need bind vaiables, you can use selectall_arrayref also:
my $res = $dbh->selectall_arrayref('select Username,Password from Users where id = ?',
{Slice=>{}}, 1
);
I want to thank everyone here for the help I have recieved so far. My next question is a bit more complicated.
So I have a database set up on my server, and I have a form on my website where I am submitting data to my MYSQL database.
After I submit the data, I am having trouble searching for it, displaying possible results, and then making those results HYPERLINKED so that the user can find out more about they are looking for.
My "common.php" script is set up like this:
<?php
$username = "XXX";
$password = "XXX";
$hostname = "XXX";
$database = "XXX";
mysql_connect($hostname, $username, $password, $database) or die
("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>��
My "insertdata.php" script is set up like this:
<?php
require("common.php");
// connect with form
$name=$_POST['firstname'];
$lastname=$_POST['lastname'];
$city=$_POST['city'];
$state=$_POST['state'];
$zip=$_POST['zip'];
$phone=$_POST['phone'];
$email=$_POST['email'];
$various=$_POST['various'];
$other=$_POST['other'];
// insert data into mysql
$query="INSERT INTO datatable
(
firstname,
lastname,
city,
state,
zip,
phone,
email,
various,
other,
)
VALUES
(
'$firstname',
'$lastname',
'$city',
'$state',
'$zip',
'$phone',
'$email',
'$various',
'$other',
)";
$result=mysql_query($query);
// if successfull displays message "Data was successfully inserted into the database".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR... data was not successfully insert into the database";
}
mysql_close();
?>��
From there, I want to make the inserted data searchable.
My problem is, when the search is completed, I want to only display the First Name and Last Name in two separate columns.
From there, I want a link displayed in a third separate column with a link in each row that says "View Record Details."
Finally, when "View Record Details" in clicked, it brings me to the correct record, formatted again in an HTML table.
The closest I have come to a solution is:
<?php
require("common.php");
$query="SELECT * FROM datatable";
$result=mysql_query($query);
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$firstname=mysql_result($result,$i,"firstame");
$lastname=mysql_result($result,$i,"lastname");
$i++;}
?>
As an additional question, when I use PDO, does that change my HTML?
Switch to PDO. Your code will look something like this:
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$sql = 'SELECT * FROM datatable';
foreach ($conn->query($sql) as $row) {
print $row['firstname'] . "\t";
print $row['lastname'] . "\n";
}
EDIT:
To link back for details add this line after the 2nd print:
print "<a href='somephp.php?idx=" . $row[ 'idx' ] . "'>link here</a>";
You'll need another php file called 'somephp.php':
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$idx = $_REQUEST[ 'idx' ];
$sql = 'SELECT * FROM datatable where idx = ?';
$stmt = $conn->prepare( $sql );
$stmt->bindParam( 1, $idx );
$stmt->execute();
$row = $stmt->fetch();
// now print all the values...
print $row['firstname'] . "\t";
print $row['lastname'] . "\t";
print $row['address'] . "\t";
and so on...
NOTE: This depends on each record having a unique key 'idx'. I don't see this in your values above so you'll have to find a way to incorporate it if you want to use this code.
ALSO: You ask - does this change the HTML and does this handle table formatting - No to both. You do all the HTML formatting via the print statements. All PHP does it output lines to the browser.
I' currently working on a scheduled task where task scheduler will run the file daily to pick up expiry date 3 months from now and send email to receipient. But at this point of time, I can't seems to think of the correct syntax to do that. This is what I have right now which is only giving me an error.
<?php
//authentication for database
$hostname = "localhost";
$username = "admin";
$password = "xxxxxx";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("notification",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM tbl_lead WHERE pass_expiry >= DATE(NOW() + INTERVAL 3 MONTHS");
//variable for email message
$emailBody = "";
$headers = 'From: Pass Validity Reminder' . "\r\n" .
'Reply-To: myemail#email.com' . "\r\n" .
'Cc: ccemail#Wemail. com' . "\r\n".
'X-Mailer: PHP/' . phpversion();
$to = "myemail#email.com";
//fetch tha data from the database
while ($row = mysql_fetch_array($result))
{
$subject = $row['company_name']."'s"." work pass is expiry soon";
$emailBody .="Creator: ".$row['rlog_create_user_name']." \n". "Email: ".$row['email']."
\n"."Comment: ".$row['comment']." \n"."Contact: ".$row['contact']." \n";
}
mail($to, $subject, $emailBody, $headers);
echo 'Email sent successfully!';
//close the connection
mysql_close($dbhandle);
?>
However, this error keeps coming up and I'm pretty sure there will be an error message also when there's no match. How can I go about perfecting this script?
( ! ) Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in
C:\wamp\www\notification\staff\notify2.php on line 27
Call Stack
# Time Memory Function Location
1 0.0005 681120 {main}( ) ..\notify2.php:0
2 1.0247 689424 mysql_fetch_array ( ) ..\notify2.php:27
( ! ) Notice: Undefined variable: subject in C:\wamp\www\notification\staff\notify2.php on line34
Call Stack
# Time Memory Function Location
1 0.0005 681120 {main}( ) ..\notify2.php:0
I have made the amendment according to #peterm recommendation and the error is gone now. However, now the email still won't send.
I added a check for the email parameters. I had echo out the result before the error message to ensure it pass through the query.
//fetch tha data from the database
while ($row = mysql_fetch_array($result))
{
$subject = $row['company_name']."'s"." work pass is expiry soon";
$emailBody .= "Company: ".$row['company_name']." \n"."Comment: ".$row['comment']."
\n"."Contact: ".$row['contact']." \n";
}
if(mail($to, $subject, $emailBody, $headers)) {
echo 'Email sent successfully!';
} else {
echo $emailBody;
die('Failure: Email was not sent!');
}
The script is suppose to check through every entry in the database and send email for each matching entry. Sorry for the coding in comment, I'm a first time user in stackoverflow and havent been in touch with programming for more than 8 years. Forgetting everything and nv heard of PDO. #peterm.
Your query fails, because SELECT has errors.
Try this one:
SELECT * FROM events WHERE event_date >= DATE(NOW() + INTERVAL 3 MONTH)
You didn't close parenthesis for DATE() function and correct INTERVAL keyword is MONTH.
Now, when a query execution fails mysql_query() returns FALSE instead of a resource. Therefore always check return value before passing $result to mysql_fetch_*:
$result = mysql_query(...);
if (!$result) {
//handle your error
die('The query failed.'); //There are certainly better ways to handle it
}
...
And please, stop using mysql_* functions for new code. They are deprecated. Use prepared statements with either PDO or MySQLi. Here is good PDO tutorial.
I am trying to get MySQL database into an xml file; here is my code:
<?php
header("Content-type: text/xml");
include 'dbc.php';
$query = "SELECT * FROM airports LIMIT 50";
$result = mysql_query($query, $link)
or die('Error querying database.');
$xml = new SimpleXMLElement('<xml/>');
while($row = mysql_fetch_assoc($result)) {
$draw = $xml->addChild('draw');
$draw->addChild('ident',htmlentities(iconv("UTF-8", "ISO-8859-1//IGNORE",$row['ident'])));
$draw->addChild('name',htmlentities(iconv("UTF-8", "ISO-8859-1//IGNORE",$row['name'])));
}
mysql_close($link);
$fp = fopen("links2.xml","wb");
fwrite($fp,$xml->asXML());
fclose($fp);
Here is the error Im getting:
XML Parsing Error: no element found
Location: /sql2xml2.php
Line Number 1, Column 2:
-^
What am I doing wrong???
Your XML is considered invalid in your XML reader because of the thrown warning, thus the XML Parsing Error: junk after document element issue.
As for the warning itself, you need to escape special entities (namely &, < and > in your content when adding it like that (using str_replace usually works well for only those 3 when it comes to XML, htmlentities may yield undesired effects, unless you supply PHP 5.4's ENT_XML1 mode).
Refer to a related answer for more information of why this happens.
If you want just to export MySQL database to local XML file you can use mysqldump tool:
mysqldump --xml -u username -p databasename [tablename] > filename.xml
Got it to work with this code:
<?
header("content-type:text/xml");
function getXML($query="SELECT * FROM airports limit 50")
{
include 'dbc.php';
$result = mysql_query($query, $link)
or die('Error querying database.');
$columns="";
echo "<xml>\n";
while($row=mysql_fetch_assoc($result))
{
$columns.="\t<airport>\n";
foreach($row as $key => $value)
{
$value = htmlentities(iconv("UTF-8", "ISO-8859-1//TRANSLIT",$value));
$value = htmlentities(iconv("UTF-8", "ISO-8859-1//IGNORE",$value));
$columns.="\t\t<$key>$value</$key>\n";
}
$columns.="\t</airport>\n";
}
echo $columns;
echo "</xml>\n";
}
getXML();
?>