Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm working on my PHP script to call the function once at a time when I click the link on my site.
When I click the link on my site to connect to the get-listing.php script, it will call to both function of tvguidecom and skyuk at the same time which it will output one of those webpage.
I think the problem are on this line:
while ($row = mysql_fetch_array($result1))
{
tvguidecom($row);
skyuk($row);
}
Here is the full code:
<?php
$errmsg_arr = array();
$errflag = false;
$link;
include ('simple_html_dom.php');
function db_connect()
{
define('DB_HOST', 'localhost');
define('DB_USER', 'mydbname');
define('DB_PASSWORD', 'mydbpassword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
}
function tvguidecom($row)
{
include ('tvguide.get-listing.php');
}
function tvguide2($row)
{
include ('skyuk.php');
}
db_connect();
function clean($var)
{
return mysql_real_escape_string(strip_tags($var));
}
$channels = "";
$id = "";
if(isset($_GET['channels']))
{
$channels = $_GET['channels'];
}
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
if($errflag)
{
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
echo implode('<br />',$errmsg_arr);
}
else
{
$insert = array();
if(isset($_GET['channels']))
{
$insert[] = 'channels = \'' . clean($_GET['channels']) .'\'';
}
if(isset($_GET['id']))
{
$insert[] = 'id = \'' . clean($_GET['id']) . '\'';
}
if($channels && $id)
{
$qrytable1="SELECT id, channels, links FROM tvguide WHERE channels='$channels' && id='$id'";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
tvguidecom($row);
skyuk($row);
}
mysql_close();
exit;
}
else if(!$channels && ! $id)
{
$qrytable1="SELECT id, channels, links, streams FROM tvguide";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
echo "<p id='channels'>".$row["id"]. " " . $row["channels"]. "</p>";
echo '<a id="link1" href="http://example.com/get-listing.php?channels=' . $row["channels"] . "&id=" . $row["id"] . '">http://example.com/get-listing.php?channels=' . $row["channels"] . "&id=" . $row["id"] . '</a><br><br>';
//echo "<p id='links'>";
//echo '<a id="link1" href="http://example.com/get-listing.php?channels=' . $row["channels"] . "&id=" . $row["id"] . "'>http://example.com/get-listing.php?channels=" . $row["channels"] . "&id=" . $row["id"] .'>test</a></p>';
//echo '<a id="link1" href="http://example.com/get-listing.php?channels=';
echo '<a id="streams" href="' . $row['streams'] . '">Stream 1</a><br><br>';
}
}
}
?>
I want to call either of function once at a time when I click the link on my site. Example: I want to call tvguidecom function to see if it will output the data in my get-listing script or else move on to the next function and call the skyuk function.
Can you please show me an example of how I can call the function once at a time when I click the link on my site?
The best thing you can do is having your functions returning a boolean so you can check if you should continue the process.
I guess the function tvguidecom looks like:
function tvguidecom() {
// do something without return value
}
Add a return value in it:
function tvguidecom() {
// do something
return $status;
}
So in your code you can test for the return value
while ($row = mysql_fetch_array($result1))
{
if (tvguidecom($row)) {
skyuk($row);
}
}
Note: on a different topic, you shouldn't use anymore mysql extension because it is deprecated. You should use instead mysqli or pdo.
TL;DR
while ($row = mysql_fetch_array($result1))
{
// this ensures that `tvguidecom()` does its stuff, and `skyuk()`
// waits for results returned by the function.
skyuk(tvguidecom($row));
}
function tvguidecom($row) {
// do stuffs, returns original input $row;
return $row;
}
** Another approach, callbacks.**
while ($row = mysql_fetch_array($result1))
{
tvguidecom($row, callback);
}
and fn:
tvguidecom(a, callback) {
// dostuffs and when complete
callback( result );
}
** syntax may be incorrect, refer to link supplied. Hope this helps.
Related
I was experimenting if I could use a mySQL database to store CSS settings. I set up a simple database "colors" with one table "color" that had simple structure tag and color columns. In that, one row is h1 => red.
<?php
//function to dynamically change CSS
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
?>
When I tried to convert to a function, the code does not work at all.
<?php
//function to dynamically change CSS
function getCSS($tag)
{
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
}
getCSS('h1');
?>
Help please?
My guess is that in
$query = mysqli_query($link, $q);
$link goes out of scope and is empty. You should pass it to the function as well.
For the record: using $tag without escaping could be an sql injection attack possibility.
in function, there is no $link, you shoud define it as a global variable.
At the start of your function add a reference to your global DB link:
function getCSS($tag) {
global $link;
...
This should work:
<?php
$link = mysqli_connect('server_host', 'user', 'password', 'database') OR die('Could not connect because: '.mysqli_connect_error());
//function to dynamically change CSS
function getCSS($link, $tag){
$q = 'SELECT * FROM colors WHERE tag = "' . $tag . '"' ;
$r = mysqli_query($link, $q);
if(mysqli_num_rows($r)>0){ // check if there are results
while($row = mysqli_fetch_assoc($r)){
//echo '<pre>';
//print_r($row); // print the result array for debugging
//echo '</pre>';
echo $row['color'] . '<br />';
}
return $row;
} else { // if no result is found
echo 'No such tag';
}
}
// test it:
echo '<br />if tag is h1<br />';
getCSS($link, 'h1');
echo '<br />if tag is h2<br />';
getCSS($link, 'h2');
?>
I am a total noob with performing OOP, and am currently looking to refactor a procedural PHP project. Currently, I am having issues trying to simply display my results from a SELECT query--ironically doing an INSERT query made sense instead. This is my Class file:
<?php
class MadLibs {
private $noun;
private $verb;
private $adverb;
private $adjective;
private $story;
// Getters
public function getNoun() {
return $this->noun;
}
public function getVerb() {
return $this->verb;
}
public function getAdverb() {
return $this->adverb;
}
public function getAdjective() {
return $this->adjective;
}
public function getStory() {
return $this->story;
}
// Setters
public function setNoun($noun) {
$this->noun = $noun;
}
public function setVerb($verb) {
$this->verb = $verb;
}
public function setAdverb($adverb) {
$this->adverb = $adverb;
}
public function setAdjective($adjective) {
$this->adjective = $adjective;
}
public function setStory($story) {
$this->story = $story;
}
// Figured this one out
public function insertStoryToDatabase() {
date_default_timezone_set('America/Chicago');
$submit_date = date('Y-m-d' . " " . 'H:i:s');
$dbc = mysqli_connect('localhost','root','','mad_libs')
or die('Error establishing connection');
$query = "INSERT INTO storyTime (noun, verb, adjective, adverb, createdDate, fullStory) " .
"VALUES ('$this->noun','$this->verb','$this->adjective','$this->adverb','$submit_date','$this->story')";
mysqli_query($dbc,$query)
or die('Error querying database');
mysqli_close($dbc);
}
// method I am having trouble setting up
public function displayAllStories() {
$dbc = mysqli_connect('localhost','root','','mad_libs')
or die('Error establishing connection');
$result = "SELECT fullStory, createdDate FROM storyTime ORDER BY createdDate DESC";
$display = mysqli_query($dbc,$result)
or die('Error gathering data!');
while ($row = mysqli_fetch_array($display)) {
echo $row['story'] . '<br/>';
}
return $display;
}
}
?>
And this is what I am doing in my other php file:
<?php
require_once('MadLibs.php');
// Instantiating instance of MadLibs()
$foo = new MadLibs();
// Playing around to see ensure getters/setters were correct
$foo->setNoun('Bob');
$foo->setVerb('jumps');
$foo->setAdverb('quietly');
$foo->setAdjective('ugly');
$foo->setStory("The " . $foo->getNoun() . " always " . $foo->getVerb() . " at the "
. $foo->getAdjective() . " strangers " . $foo->getAdverb() . ".");
echo $foo->getNoun();
echo '<br />';
echo $foo->getVerb();
echo '<br />';
echo $foo->getAdverb();
echo '<br />';
echo $foo->getAdjective();
echo '<br />';
echo $foo->getStory();
$foo->insertStoryToDatabase();
$foo->displayAllStories();
?>
I'm sure it's something simple, but for the life of me I can't figure out what I'm doing wrong.
Any and all feedback is most appreciated!
You trying to display wrong variable in displayAllStories() function .
'echo $row['story']should be change to$row['fullStory'];` or change your query to
SELECT fullStory as story, createdDate FROM storyTime ORDER BY createdDate DESC
this is my first question here so please do not roast on me.
I am currently working on a html, php, mysql project in school and I want to know if it is possible to compare the entry of a form in html with a table in my database to get its id.
The form looks like
Prename:""
Last name:" "
The table:
ID: '1'
Prename:'abc'
Last name: 'xyz'
Now, if someone fills out the form and submit, I want to send it to a function which looks through the database and if a match is found, returns the ID.
Thanks for your ideas!
Edit: As you want here is what I got so far includes the code from #Patchesoft
Still it isnt working
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="db_class.php" method="post">
<p>Vorname: <input type="text" name="prename"/></p>
<p>Nachname: <input type="text" name="last_name"/></p>
<input type="submit" name="submit" value="Start"/>
</form>
</body>
</html>
And for the PHP part our teacher got us a class with a lot of functions to add and select from databases etc. The most important:
<?php
DB::init(...); // The connection is ok. I just delted the login data for purpose
$prename = mysqli_real_escape_string($_POST['prename']);
$lastname = mysqli_real_escape_string($_POST['last_name']);
$result = mysqli_query("SELECT `ID` FROM `user` WHERE `prename` = '" . $prename . "' AND `last_name` = '" . $lastname . "' ");
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
return $row['ID'];
}
echo $result;
class DB {
public static $db = null;
public static $insertID;
public static function init($dbHost, $dbUser, $dbPassword, $dbName) {
self::$db = new mysqli($dbHost, $dbUser, $dbPassword, $dbName);
if (self::$db->connect_errno) {
$_SESSION['errors'][] = "MySQL connection failed: ". self::$db->connect_error;
}
self::$db->query("SET NAMES utf8;");
}
public static function select($table, $columns = '*', $key=null, $where = null, $limit = null, $debug = false) {
$sql = "SELECT " . self::generateColumnList($columns) . " FROM $table";
if ($where != null) {
$sql .= " WHERE ".$where;
}
if ($limit != null) {
$sql .= " LIMIT ".$limit;
}
if ($debug == true) {
$_SESSION['debug'][] = __FUNCTION__ . ': $sql is <strong>' . $sql . '</strong>';
}
$result = self::$db->query($sql);
if (self::$db->errno) {
$_SESSION['errors'][] = '<p>select failed: ' . self::$db->error . '<br> statement was: <strong>' . $sql . '</strong></p>';
return array();
} else {
$ret = array();
while ($row = $result->fetch_assoc()) {
if (!empty($key)){
$ret[$row['id']] = $row;
}
else
$ret[] = $row;
}
if (count($ret) == 1) {
return $ret[0];
} else {
return $ret;
}
}
}
public static function select2($sql, $debug = false) {
$result = self::$db->query($sql);
if (self::$db->errno) {
$_SESSION['errors'][] = '<p>select failed: ' . self::$db->error . '<br> statement was: <strong>' . $sql . '</strong></p>';
return array();
} else {
$ret = array();
while ($row = $result->fetch_assoc()) {
if (!empty($key)){
$ret[$row['id']] = $row;
}
else
$ret[] = $row;
}
if (count($ret) == 1) {
return $ret[0];
} else {
return $ret;
}
}
}
You will want to get your form input fields into variables and then make an SQL query that checks the data in your database. It's quite simple, but for a beginner there are some other things to consider.
1) Sanitizing your input. This is important to protect against SQL Injection attacks. The simple answer is to run it through mysql_real_escape_string() function to clean the variable, but there are much more better methods than this. Look up prepared statements.
2) Connecting to your database. Before you can do any querying to your database, you need to connect to it. It's quite simple to do, but you will need to look up how to do this.
As for some base code, try:
$prename = mysqli_real_escape_string($_POST['prename']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
// Now check to see if the values match in your database
// This assumes you have already written your connecting to database code
$result = mysqli_query("SELECT `ID` FROM `table_name` WHERE `prename` = '" . $prename . "' AND `lastname` = '" . $lastname . "' ");
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
return $row['ID'];
}
This is a very basic script- it's what I as a beginning learned doing. There are much better ways of doing it, using PDO database drivers. But if you're just learning to do something in PHP and MySQL, this should get you going.
I am trying to figure out how to use this in a loop. Any help will be appreciated.
$conn = mysql_connect("localhost", "some_user", "password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("some_db")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT favid FROM ajaxfavourites";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"];
}
mysql_free_result($result);
Currently it displays results as:
116677889922
I need them to show them as (the way they are displayed in DB):
1166
7788
9922
PS I am aware that this function is deprecated, I am just trying to fix one of my older sites.
choose One of these ways:
echo $row["favid"]."<br>";
echo $row["favid"]."\n";
echo $row["favid"].PHP_EOL;
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"];
echo "\r\n";
}
You can simply echo the value with '<br/>' or '<p>' like following:
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"] . '<br/>';
}
OR
while ($row = mysql_fetch_assoc($result)) {
echo '<p>' . $row["favid"] . '</p>';
}
Also you can just put all favid into array and then in another loop, can customize how to show them, like following:
while ($row = mysql_fetch_assoc($result)) {
$ids[] = $row["favid"];
}
foreach($ids AS $idv) {
echo '<p>' . $idv . '</p>';
}
I'm stored the website link in MYSQL database where I can output the data in PHP and I'm using PHP DOM to extract the data. I have output the text which I got "CBS This Morning: Saturday NEW" using this code:
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'myusername');
define('DB_PASSWORD', 'mypassword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
function clean($var)
{
return mysql_real_escape_string(strip_tags($var));
}
$channels = clean($_GET['channels']);
$id = clean($_GET['id']);
if($errflag)
{
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
echo implode('<br />',$errmsg_arr);
}
else
{
$insert = array();
if(isset($_GET['channels']))
{
$insert[] = 'channels = \'' . clean($_GET['channels']) .'\'';
}
if(isset($_GET['id']))
{
$insert[] = 'id = \'' . clean($_GET['id']) . '\'';
}
if($channels && $id)
{
$qrytable1="SELECT id, channels, links FROM tvguide WHERE channels='$channels' && id='$id'";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
$links = $row['links'];
include ('simple_html_dom.php');
$html = file_get_html($links);
$title1 = $html->find('li[id=row1-1]', 0)->plaintext; // with this
if ($html->find('li[id=row1-1]', 0)->plaintext == ('NEW'))
{
$output = preg_replace('/\d:\d+/', '', $title1);
$output = '<span id="title1">'.str_replace(array("\t", ' ', '<BR>','</BR>', 'AM','PM'), '', $output).'</span><br><br>';
$output = str_replace('<span id="title1"> ', '<span id="title1">', $output);
$output = str_replace(' "', ': ', $output);
$output = str_replace(' NEW', '', $output);
echo $output;
}
}
}
?>
Here's the HTML source:
<span id="title1">CBS This Morning: Saturday NEW</span><br><br>
In this case, I'm trying to look for a contain text at the end whether if the conttain text have a text called "NEW" then it will be replaced to an empty text. I tried to use it with if ($html->find('li[id=row1-1]', 0)->plaintext == ('NEW')) to look for a contain text before do something, but it doesn't check it out. I think I might have done it wrong, but I'm not really sure. Does anyone know how I can check for a contain text at the end of the text using if statement so I can replace the contain text to an empty text?
== does an exact match of the entire string. You need to use a function that searches for a substring:
if (strpos($title1, 'NEW') !== false) {
...
}
If you only want to recognize it at the end of the title, you can use a regular expression:
if (preg_match('/NEW$/', $title1) {
...
}
or you could use substr():
if (substr($title1, -3) == 'NEW') {
...
}