error grabbing ad code from database using mysql - php

I am trying to grab ad code from my database and echo it on to the page, but for some reason it is not showing up?
$getad = ("SELECT * FROM ads WHERE place='non-mobile' AND who='adbrite' ");
while($rows = mysql_fetch_array($getad))
{
$code = $rows['code'];
}
$ad1 = $code;
later down the page i print it like this.
<?php print $ad1 ?>

I think your problem is that you don't actually execute the query, you just have saved it in a variable ($getad) and then try to do a fetch af an array containing a string as I see it. If I remeber correctly you have to save you query in a variable, as you did, and then type
$getad = "SELECT * FROM ads WHERE place='non-mobile' AND who='adbrite' ";
$q = $db->query($getad);
// generate results:
while ($q->fetchInto($row)) {
//display or store
}
You should also include checks, for example that this code has extracted at least one row, or that database connection is working, etcetera.

Related

Check if value is found in SQL table within PHP script?

I need to be able to check and see in a certain string is anywhere within my SQL table. The table I am using only has one column of char's. Right now it is saying that everything entered is already within the table, even when it actually is not.
Within SQL I am getting the rows that have the word using this:
SELECT * FROM ADDRESSES WHERE STREET LIKE '%streeetName%';
However, in PHP the word is being entered by the user, and then I am storing it as a variable, and then trying to figure out a way to see if that variable is somewhere within the table.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one of each address allowed.<br /><hr>";
}
You need to do a little bit more than building the query, as mysql_query only returns the resource, which doesn't give you any information about the actual result. Using something like mysql_num_rows should work.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(mysql_num_rows($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
Note: the mysql_* functions are deprecated and even removed in PHP 7. You should use PDO instead.
In the SQL you used
%streeetName%
But in the query string below, you used
%$streeetName%
Change the correct one
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
if($results->num_rows) is what you need to check if you have results back from your query. An example of connection and query, check, then print or error handle, the code is loose and not checked for errors. Best of luck...
//Typically your db connect will come from an includes and/or class User...
$db = new mysqli('localhost','user','pass','database');
$sql = "SELECT * FROM `addresses` WHERE `street_name` LIKE '%$streetName%'",$connect;
//test your queries in PHPMyAdmin SQL to make sure they are properly configured.
//store the results of your query in a variable
$results = $db->query($sql);
$stmt = '';//empty variable to hold the values of the query as it runs through the while loop
###########################################################
#check to see if you received results back from your query#
###########################################################
if($results->num_rows){
//loop through your results and echo or assign the values as needed
while($row = $results->fetch_assoc()){
echo "Street Name: ".$row['STREET_NAME'];
//define more variables from your DB query using the $row[] array.
//concatenate values to a variable for printing in your choice further down the document.
$address .= $row['STREET_NAME'].' '.$row['CITY'].' '$row['STATE'].' '$row['ZIP'];
}
}else{ ERROR HANDLING }

Get data from MYSQL using PHP returns no results

So I am using this tutorial: https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/ to try and get data from my local MYSQL server (using Wamp64). I had the undefined index error at first, which I fixed using the isset() statement.
But now it just returns:
{"result":[]}
I have, however, a lot of data in the set column of that database.
Here is the code:
<?php
//Getting the requested klas
$klas = isset($_GET['klas']) ? $_GET['klas'] : '';
//Importing database
require_once('dbConnect.php');
//Creating SQL query with where clause to get a specific klas
$sql = "SELECT * FROM lessen WHERE klas='$klas'";
//Getting result
$r = mysqli_query($con,$sql);
//Pushing result to an array
$result = array();
while ($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id"=>$row['id'],
"klas"=>$row['klas'],
"dag"=>$row['dag'],
"lesuur"=>$row['lesuur'],
"les"=>$row['les'],
"lokaal"=>$row['lokaal']
));
}
//Displaying the array in JSON format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I tried out the
SELECT * FROM lessen WHERE klas='$klas'
statement in my database and it seems to return the correct data.
Any idea what is causing this?
Thanks in advance!
Point 1 is:
isset function only checks if klas is set in the $_GET global array. So if somehow $klas is blank - your query will return empty (without giving error).
So please check values in the $_GET and possibly from where it is accessed. Or you can add condition to avoid empty query like --
if (!empty($_GET['klas'])) {
// rest of the code block upto return
Point 2 is:
You have mentioned if you echo the sql it returns
SELECT * FROM lessen WHERE klas=''{"result":[]}
Here the second part (the JSON) is from echoing the result at the end of your code. So for the first part (i.e. echoing $sql) we see that klas=''. That actually goes to the Point 1 as mentioned above.
So finally you have to check why the value at $_GET is showing blank. That will solve your problem.
UPDATE:
From #GeeSplit's comment For the request
"GET /JSON-parsing/getKlas.php?=3ECA"
There will be nothing in $_GET['klas'] cause the querystring in the url doesn't contain any key.
So either you have to change the source from where the file is called. Or you can change how you are getting the value of klas.
Example:
$tmpKlas = $_SERVER['QUERY_STRING'];
$klas = ltrim($tmpKlas, '=');
Rest of your code will work.
Use this code
<?php
$klas ='';
if(isset($_GET['klas']) && !empty($_GET['klas']))
{
$klas = $_GET['klas'];
require_once('dbConnect.php');
$sql = 'SELECT * FROM lessen WHERE klas="'.$klas.'"';
$r = mysqli_query($con,$sql);
$result = array();
while ($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id"=>$row['id'],
"klas"=>$row['klas'],
"dag"=>$row['dag'],
"lesuur"=>$row['lesuur'],
"les"=>$row['les'],
"lokaal"=>$row['lokaal']
));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
}
?>

Display PHP code on web page

I am creating a library for PHP scripts and I want to be able to show php code on a html webpage.
I have looked at using highlight_file(); but this will show the whole page
For example, If I have a page called code.php which has an sql query on ( select code from table where sequence = $_GET["id"] ) - example then I use
Highlight_file('code.php?id=123');
This will work but will also show the select query which I do not want to show. I would just want to show the code from the database (code column)
How can I display just the code from the database with the correct colours and formatting etc
UPDATE:
<?php
$conn=mysql_connect("localhost","charlie_library","Pathfinder0287");
mysql_select_db("charlie_library",$conn);
function highlight_code_with_id($id, $conn)
{
$query = "select * from library_php where sequence = '$id' ";
$rs = mysql_query($query,$conn);
$code = mysql_fetch_array($rs);
echo highlight_string($code["code"]);
}
// and, use it like this:
highlight_code_with_id($_GET['id'], $conn);
?>
I have tried the above code, which is just displaying the code in plain text
use highlight_string function, like this:
<?php
highlight_string($code);
?>
where $code is the code you have obtained from your SQL query.
You can create a function around this (something along the following lines):
<?php
function highlight_code_with_id($id, $mysqli) {
$query = $mysqli->query("select code from table where sequence = '$id'");
$code = current($query->fetch_assoc());
return highlight_string($code);
}
// and, use it like this:
echo highlight_code_with_id($_GET['id'], $mysqli);
UPDATE:
Your code is a bit incorrect, you can use:
<?php
$conn=mysql_connect("localhost","charlie_library","Pathfinder0287");
mysql_select_db("charlie_library",$conn);
function highlight_code_with_id($id)
{
$query = "select * from library_php where sequence = '$id' ";
$rs = mysql_query($query);
$code = mysql_fetch_assoc($rs); // change is in this line
echo highlight_string($code["code"]);
}
// and, use it like this:
highlight_code_with_id($_GET['id']);
?>
Note that you do not need to include $conn in your function, it can be ommitted. Also, note that you should use mysqli->* family of functions, since mysql_* family has been deprecated.
Perhaps this would work for you.
This post is originally for HTML, but the answer linked above shows an example using PHP.

Obtain Column name(s) of database via PHP

I have a postgresql database and I am connecting to and reading from it via php. Ive put in php codes that give me back the result to the query i pass from my code.
Ex- My code :(Note - My HTML page uses a form which asks for input and searches for the given input in the database)
<?php
$result = pg_prepare($dbh, "Query1", 'SELECT * FROM test.bact WHERE disease = $1');
$result = pg_execute($dbh, "Query1", array($disease));
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
//$rows = pg_fetch_all($result)
/*// iterate over result set
// print each row*/
while ($row = pg_fetch_array($result)) {
echo $row[0]." ".$row[1]. "<br />";
}
From the above piece of code I get my information as strings separated by a space ( echo $row[0]." ".$row[1])
example: Information at row[0]<space>Information at row[1]
What I want - I want the retrieved data in a more organised form i.e. with the column name.
How it should look like -
Name of Column : Data
Name of column : Data ...and so on.
I know there is way in mysql using the mysql_fetch_field, but I wanted something for postgresql. Since I am new to php n databases I am not really sure as to how will I use this.
Any help would be appreciated.
You can use pg_field_name or pg_fetch_assoc

URL and link text from database

I am currently still learning PHP so some things I still struggle with.
I have been taking it slowly and reading tutorials which has helped but I can't figure this one out.
I have a database table (in mysql) with let's say, 100 urls. There is a column called 'url' and a second column 'text'. I already have the pagination code which works, so will also be using that.
What I want to do is echo out the URLs (which are all in folder called blog in the root of my site), but use the text as the link.
So for example the first three rows in my table might be:
url
001.php
002.php
003.php
text
random text
some random text
more text
when echoed out the links show the text from the column text like:
random text
some random text
more text
and will open to the relevant url when clicked
I'm guessing it will need some kind of loop to collect all the URLs and save me adding the link text in manually, and then my pagination code will split them up.
This is my first time asking a question on here, so if it wasn't clear enough or you need more info, let me know.
I have done multiple searches on the internet but can't seem to find a tutorial.
Assuming you connect to a local mysql server with username "root" and password "root", and have your url's stored in a table named url_table in a database named url_database you could do something like:
$connection = mysql_connect("127.0.0.1","root","root"); // Connect to the mysql server
mysql_select_db("url_database"); // Open the desired database
$query = "SELECT url,text FROM url_table"; // Query to select the fields in each row
$result = mysql_query($query); // Run the query and store the result in $result
while($row = mysql_fetch_assoc($result)) // While there are still rows, create an array of each
{
echo "<a href='".$row['url']."'>".$row['text']."</a>"; // Write an anchor with the url as href, and text as value/content
}
mysql_close($connection); // close the previously opened connection to the database
What you need is to:
get your result array from the database. Use something like
$query = "SELECT * FROM urls";
$result = mysql_query($query);
For every row in your results table, show the corresponding url. Note that calling mysql_fetch_array on a result resource, returns the first row of the results table when called for the first time, the second on second time etc. The function returns false when there are no more rows to return.
(See more on that in the mysql_fetch_array() documentation)
While( $row = mysql_fetch_array($result) ){
echo '<a href='.$row['url'].'>'.$row['text'].'</a>';
}
Here is a sample you can start with:
$con = mysql_connect("host","user","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT the_url, the_text FROM my_table");
while($row = mysql_fetch_array($result))
{
echo '"' . $row['the_text'] . ' <br />';
}
mysql_close($con);
First, you want to select only the relevant lines in your database for the page that the user is currently viewing. For example, if the user is viewing page 2, with entries 15-30 present, we only want to pull those entries from the database. This is an efficiency concern.
The code you're after is something like this:
$link = mysql_connect(/*connection parameters go here*/);
if ($link === false)
die;
mysql_select_db('my_database');
$result = mysql_query("SELECT text, url FROM my_table LIMIT 15,30");
print "<ul>\n";
while ($row = mysql_fetch_assoc($result)) {
print "<li>{$row['text']}</li>\n";
}
print "</ul>\n";
mysql_close();
The first three lines establish a connection to the database, and exit the script if an error occurs.
The next line selects the appropriate database on the server.
The next block runs the appropriate query for the second page. After the query is run, a 'result' is stored in $result. This result is comprised of a number of rows, and mysql_fetch_assoc($result) obtains those lines one at a time. It then formats these lines into the appropriate link format and outputs them. The entire set of links is wrapped in a dot-point list.
Finally, mysql_close() closes the connection to the database.
I'm assuming since you just started you're probably doing all this procedurally.
First you want to query the database and get the info you need.
<?php
$result = mysqli_query($link, "SELECT url, text FROM table_name");
while ($row = mysqli_fetch_array($result)) $hrefs[] = $row;
foreach ($hrefs as $href) {
echo "".$href['text']."";
}
?>
Please note I've done no error handling here.

Categories