I am trying to write a function that will fetch one column from mysql & return it. some how I am not able to write get_hash() function. Further is it safe to use $GLOBALS?
<?php
//Create Database Connection
$dbhost = "localhost";
$dbuser = "developer";
$dbpass = "abc";
$dbname = "abc";
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
//Test Connection`enter code here`
if(mysqli_connect_errno()) {
die("Connection Failed" .
mysqli_connect_error() .
"(" . mysqli_connect_errorno() . ")"
);
}
// Query
$query = "SELECT tweet FROM twc_hashtag";
// Fetch Data
function get_hash() {
if ($result=mysqli_query($GLOBALS['connection'], $GLOBALS['query'])){
while ($row=mysqli_fetch_row($result)){
//echo "<tr>";
//echo "<td>" . $row[0] . "</td>";
//echo "</tr>";
return $row[0];
}
}
//Test Query Error
if(!$result){
die("Database Query Failed" . mysqli_error($GLOBALS['connection']));
}
}
//Close The Connection
mysqli_close($connection);
?>
I need to fetch the data in a different php file & then pass that data to a javascript function. Hence I am going to call get_hash(); from a different php file.
Related
I am creating a database to make my 'PHP' website but I couldn't do this. My website is cruzapp that is related to rideshare companies and changing it in to php to get details about our users. But I can't connect MYSQL by using the following PHP code:
?php
$username = "name";
$password = "password";
$hostname = "host";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Not connected to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT id, model,year FROM cars");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:"$row{'id'}." Name:".$row{'model'}."Year: ". //display the results
$row{'year'}.<br>";
}
//close the connection
mysql_close($dbhandle)
?>
Can anyone help me to debug this code?
I will be very thankful to you.
Try this one out. It uses MySQLi with error echoing.
<?php
$username = "name";
$password = "password";
$hostname = "host";
$database = "examples";
$con = mysqli_connect($hostname, $username, $password, $database);
if (!$con) {
exit("Connection failed: " . mysqli_connect_error());
}
$result = mysqli_query($con, "SELECT id, model,year FROM cars");
if (mysqli_error($con)) {
exit("Error: " . mysqli_error($con));
}
while ($row = mysqli_fetch_array($result)) {
echo "ID:" . $row['id'] . " Name:" . $row['model'] . "Year: " . $row['year'] . "<br>";
}
mysqli_close($con);
First of all you should not use mysql because with PHP 7 mysql extension does not work anymore. so you must consider to change it to mysqli or PDO. PDO is recommended. Any how for a quick fix $selected = mysql_select_db($dbhandle,"examples") do this and also check all your values like hostname database name table name and make sure there are no mistakes.
mysql_fetch_array() expects parameter 1 to be resource, boolean given in
<?php
mysql_connect ("localhost", "cab","a321") or die (mysql_error());
mysql_select_db ("ppwxpjey_mcidb");
$termOrd = $_POST['termOrd'];
$sql = mysql_query("select * from booking where order_no like '%$termOrd%'");
while ($row = mysql_fetch_array($sql)){
echo "<table width='1000' border='2' align='center' style='background-color:#FFFFFF;border-collapse:collapse;border:2px solid #6699FF;color:#000000'><tr><th>ORDER NO</th><th>NAME</th><th>MOBILE</th><th>FROM PLACE</th><th>TO PLACE</th><th>JOURNEY DATE</th><th>JOURNEY TIME</th><th>PERSON</th><th>BOOKING TIME</th></tr>";
echo "<tr><td>".$row["ORDER_NO"]."</td><td>".$row["NAME"]."</td><td>".$row["MOBILE"]."</td><td>".$row["FROM_PLACE"]."</td><td>".$row["TO_PLACE"]."</td><td>".$row["JOURNEY_DATE"]."</td><td>".$row["JOURNEY_TIME"]."</td><td>".$row["PERSON"]."</td><td>".$row["UPDATE_TIME"]."</td></tr>";
echo '<br/>';
}
?>
You've to run the query before passing it in mysql_fetch_array which expects resource as a parameter. So change your code like this,
$sql = mysql_query("select * from booking where order_no like '%$termOrd%'");
$result = mysql_query($query) or die(mysql_error());
// This is where you're getting resource or throwing SQL error.
while ($row = mysql_fetch_array($result)){
// YOUR LOGIC.
}
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed
in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be
used. Source : http://php.net/manual/en/function.mysql-query.php
So update your code as soon as you can.
Use mysqli_* or PDO . mysql_* is deprecated.
The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MYSQLi or PDO_MySQL extensions. use prepared statement
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "cab"; //username
$password = "a321"; //password
$mysql_database = "ppwxpjey_mcidb"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
$termOrd = "%{$_POST['termOrd']}%";
$stmt = $conn->prepare("select * from booking where order_no like ? ");
$stmt->bind_param('s',$termOrd);
$stmt->execute();
$get_result= $stmt->get_result();
$row_count= $stmt->affected_rows;
if($row_count>0)
{
while($row=$get_result->fetch_assoc())
{
echo "<table width='1000' border='2' align='center' style='background-color:#FFFFFF;border-collapse:collapse;border:2px solid #6699FF;color:#000000'><tr><th>ORDER NO</th><th>NAME</th><th>MOBILE</th><th>FROM PLACE</th><th>TO PLACE</th><th>JOURNEY DATE</th><th>JOURNEY TIME</th><th>PERSON</th><th>BOOKING TIME</th></tr>";
echo "<tr><td>".$row["ORDER_NO"]."</td><td>".$row["NAME"]."</td><td>".$row["MOBILE"]."</td><td>".$row["FROM_PLACE"]."</td><td>".$row["TO_PLACE"]."</td><td>".$row["JOURNEY_DATE"]."</td><td>".$row["JOURNEY_TIME"]."</td><td>".$row["PERSON"]."</td><td>".$row["UPDATE_TIME"]."</td></tr>";
echo '<br/>';
}
}
$stmt->close();
$conn->close();
Hi I have a search function in my index.php page. When a user types in a field and enters 'search' it goes to jobsearch.php and prints out the job summary from a mysqli database.
I've created links that go on the end of the results. So when the user sees the job summary the user clicks on the link (click here) then it directs the user to a pop up view which shows more information (job _description) about the job. Is there a way of doing this? I don't want to have to create a html page for every job as there could be 100s of jobs in the database.
I would like the click-here link to take the ID of the desired job and print out the job description on a pop up page.
It looks like this:
this is jobs.php which prints out a list of jobs..
<?php
$servername = "*****";
$username = "root";
$password = "*****";
$dbname = "jobslist";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, job_title, job_description, job_location, job_category FROM jobs_list";
$result = $conn->query($sql);
//display table
echo "<table border='1'>
<!--<tr>
<th>ID</th>
<th>Title</th>
<th>Description</th>
<th>Location</th>
<th>Category</th>
</tr>-->";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td min-height:'200' ><h2>". $row["id"] ."</h2></td>";
echo "<td>". $row["job_title"] . "</td>";
echo "<td min-width:'700' >". $row["job_description"] . "</td> " ;
echo "<td>". $row["job_location"] . "</td>";
echo "<td>". $row["job_category"] . "</td> " ;
//this prints out a clickable link for every job
echo "<td><a href='" . $row['id'] . "'>Click Here</a></td>";
echo "</tr>";
}
}
else {
echo "0 results";
}
echo "</table>";
$conn->close();
?>
Change
//this prints out a clickable link for every job
echo "<td><a href='" . $row['id'] . "'>Click Here</a></td>";
To
echo "<td><a target='jobdescriptionwindow' href='jobdescription.php?id=" . $row['id'] . "'>Click Here</a></td>";
This will open a new window (called 'jobdescriptionwindow') when you click on the link passing the ID of the job clicked through to jobdescription.php. You will also have to make sure that your browser isn't stopping this window from opening.
Create a new PHP document called jobdescription.php with these contents:
<?php
if (isset($_GET['id'])) { // Check ID is is present in parameters
$servername = "*****"; // <-- Enter your details
$username = "root";
$password = "*****"; // <-- Enter your details
$dbname = "jobslist";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// I do: (int)$_GET['id'] to type cast the value of $_GET['id'] to protect against injection. http://php.net/manual/en/language.types.type-juggling.php
$sql = "SELECT id, job_title, job_description, job_location, job_category FROM jobs_list WHERE id = ".(int)$_GET['id'];
$result = $conn->query($sql); // <-- Added new line
$row = $result->fetch_assoc();
echo $row['job_title'] . '<br />';
echo $row['job_description']; //<-- Does now show your description?
var_dump($result); // Lay out this data as required
// Outputs object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(5) ["lengths"]=> array(5) { [0]=> int(1) [1]=> int(23) [2]=> int(102) [3]=> int(4) [4]=> int(2) } ["num_rows"]=> int(1) ["type"]=> int(0) }
} else {
echo "No ID provided";
}
This will get the details for the job ID sent in the GET parameters.
You do not need to generate a page for every job. You could generate one php that gets a job id as a GET parameter (getJob.php?id=5), fetches the data from data base on that id and returns the data as HTML page.
In addition to beingalex's code, you could also use fancybox to load content in the popup via ajax instead of a new window.
See this page:
http://fancyapps.com/fancybox/
Take a look at examples specifically ajax.
Search for 'ajax' on this page.This is what you need exactly.
jobs.php href-->
echo "<td><a href='something.php?id=".$row['id']. "'>Click Here</a></td>";
Something.php:
if(isset($GET_['id'])){
$getid = $_GET['id'];
$sql = "SELECT job_title, job_description, job_location, job_category FROM jobs_list WHERE id = '".$getid."'";
$result = $conn->query(sql);
while($row = $result->fetch_assoc()){
echo $row['job_title'].'<br />';
echo $row['job_description'].'<br />;
echo $row['job_location'].'<br />;
echo $row['job_category'];
}
}
But this code is attackable with SQL Injection! You need to escape the $_GET param, or you need to learn / use PDO.
Include jQuery,Bootstrap and show information on modal popup. The modal windows opens on job title link click.
<?php
$servername = "*****";
$username = "root";
$password = "*****";
$dbname = "jobslist";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, job_title, job_description, job_location, job_category FROM jobs_list";
$result = $conn->query($sql);
$tbdata = "";
$modals = "";
if ($result->num_rows > 0) {
// display table if results exist
echo "<table class=\"table table-striped\"><tr><th>Job Title</th><th>Location</th><th>Category</th></tr>";
while($row = $result->fetch_assoc()) {
$tbdata.="<tr><td>". $row["job_title"] . "</td><td>". $row["job_location"] . "</td><td>". $row["job_category"] . "</td></tr>";
$modals.="<div class=\"modal fade\" id=\"#jbinfo_". $row["id"] . "\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"jbLabel". $row["id"] . "\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h4 class=\"modal-title\" id=\"jbLabel". $row["id"] . "\">". $row["job_title"] . "</h4></div><div class=\"modal-body\">". $row["job_description"] . "</div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button></div></div></div></div>";
}
echo $tbdata;
echo "</table>";
echo $modals;
} else {
echo "No results";
}
$conn->close();
?>
Before your closing body tag place the following:
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
basically I'm trying to pass an array from PHP to JavaScript, so far it is all working the methods I'm using are:
PHP:
echo json_encode($arrayname);
JavaScript:
$.getJSON( 'myphppage.php', {}, function(data){
// Do stuff here
});
Obviously this echo's the text onto my webpage but I do not want this text to be displayed, I'm just wondering if there is anyway for me to use this without having a chunky array at the top of my webpage. (I tried it without the echo and it doesn't work, I've also gone through countless tutorials on this but no one seems to do it without using echo)
Thanks a lot in advance
---------- Edit -------------
index.js
$.getJSON( 'myphppage.php', {}, function(data){
// I loop through the data here
}
}).done(function() {});
myphppage.php
<?php
$servername = "name";
$username = "username";
$password = "";
$dbname = "dbname";
$connection = mysql_connect($servername,$username);
if(!$connection) {
die("Database connection failed: " . mysql_error());
}else{
$db_select = mysql_select_db($dbname,$connection);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
$result = mysql_query("select * FROM tablename");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$array= array();
while($row = mysql_fetch_array($result)) {
array_push($array, $row);
}
echo json_encode($array);
}
Minimal example:
index.html
$.getJSON( 'myphppage.php', {}, function(data){
// Do stuff here
});
myphpwebpage.php
echo json_encode($arrayname);
Any ideas on Exporting HTML5 Form data to CSV please?
I can only use HTML5 or Javascript or both.
Thanks
You could just display the form data in CSV format in the browser (maybe in a popup) and have the user do a File -> Save Page (assuming it doesn't have to be fully automated).
OK, this is what I'm going to have to do: 1. If there IS internet connection ... then save the data to MySQL Table. 2. Using PHP run a script on the MySQL DB to export the data to CSV.
I'll use something like this for example:
<?php
$host = 'localhost';
$user = 'mysqlUser';
$pass = 'myUserPass';
$db = 'myDatabase';
$table = 'products_info';
$file = 'export';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>