echo a single line from a database - php

I am kind of stuck since I never tried to get something from the database in this way.
My problem:
I have a single line of code that goes to a website for example src = "www.youtube.com" however that link is stored in a database that has 1 single table called link so i retrieve this link like this
$sql = $db->prepare("SELECT link FROM youtubevid");
I have always used id's but for this table there is no need because it will get updated and i only need that 1 link. My question is how do i echo this?
Help is much appreciated
Thanks!

I guess you are using PDO to do that, if that's the case then you need to execute the query and fetch the result, after the line that you have specified i.e after the.
$sql = $db->prepare("SELECT link FROM youtubevid");
Here is the complete code:
// prepare the query
$sql = $db->prepare("SELECT link FROM youtubevid");
// execute it
$sql->execute();
// fetch the result
$result = $sql->fetch();
// echo out the column.
echo $result['link'];

Related

SQL LIKE Operator not returning rows

This is my MySQL statement, I want to search record by status or description.. this statement works fine in phpMyAdmin, but it is not working in php script.. Any Suggestions Please..
$result = mysqli_query($mysqli,
"SELECT * FROM `statuses`
where statuses.`status` LIKE '%$search%' OR
statuses.`description` LIKE '%$search%'");
I hope you write everything correct but there may be error in how you fetching data. Here are the things you need to check.
check your connection string
If you are retrieving data then use something like below
while($row = $result->fetch_array())
{
echo $row['example_col_name'];
}
You can do one more thing if everything alright store your query to a variable and echo out that one then you will see what query is passing .

Assign MySQL database value to PHP variable

I have a MySQL Database Table containing products and prices.
Though an html form I got the product name in a certain php file.
For the operation in this file I want to do I also need the corresponding price.
To me, the following looks clear enough to do it:
$price = mysql_query("SELECT price FROM products WHERE product = '$product'");
However, its echo returns:
Resource id #5
instead a value like like:
59.95
There seem to be other options like
mysqli_fetch_assoc
mysqli_fetch_array
But I can't get them to output anything meaningful and I don't know which one to use.
Thanks in advance.
You will need to fetch data from your database
$price = mysql_query("SELECT price FROM products WHERE product = '$product'");
$result = mysql_fetch_array($price);
Now you can print it with
echo $result['price'];
As side note I would advise you to switch to either PDO or mysqli since mysql_* api are deprecated and soon will be no longer mantained
If you read the manual at PHP.net (link), it will show you exactly what to do.
In short, you perform the query using mysql_query (as you did), which returns a Result-Resource. To actually get the results, you need to perform either mysql_fetch_array, mysql_fetch_assoc or mysql_fetch_object on the result resource. Like so:
$res = mysql_query("SELECT something FROM somewhere"); // perform the query on the server
$result = mysql_fetch_array($res); // retrieve the result from the server and put it into the variable $result
echo $result['something']; // will print out the result you retrieved
Please be aware though that you should not use the mysql extension anymore; it has been officially deprecated. Instead you should use either PDO or MySQLi.
So a better way to perform the same process, but using for example the MySQLi extension would be:
$db = new mysqli($host, $username, $password, $database_name); // connect to the DB
$query = $db->prepare("SELECT price FROM items WHERE itemId=?"); // prepate a query
$query->bind_param('i', $productId); // binding parameters via a safer way than via direct insertion into the query. 'i' tells mysql that it should expect an integer.
$query->execute(); // actually perform the query
$result = $query->get_result(); // retrieve the result so it can be used inside PHP
$r = $result->fetch_array(MYSQLI_ASSOC); // bind the data from the first result row to $r
echo $r['price']; // will return the price
The reason this is better is because it uses Prepared Statements. This is a safer way because it makes SQL injection attacks impossible. Imagine someone being a malicious user and providing $itemId = "0; DROP TABLE items;". Using your original approach, this would cause your entire table to be deleted! Using the prepared queries in MySQLi, it will return an error stating that $itemId is not an integer and as such will not destroy your script.

If ID from db row matches id from PHP GET function, return x page

basically I want to display a row from my database when the id from a get id switch statement matches the id from said row in the database. I'm confusing myself here so let me explain further.
If the url is www.example.com/index.php?id=2
I want the row with the id of 2 to be displayed on the page.
Here is an example of what is in the database;
id = 2
name = john
id = 3
name = mark
So if the id in the URL is equal to 2, then display id 2 and name john.
But if the id in the URL is equal to 3, then display id 3 and name mark.
I'm using a get function to do this but I'm not sure how to basically get the two ids to compare themselves and get the respective row from the database.
I'm quite new to PHP as well, so small words please! :)
Revision 2.
Like I said above, I'm new to PHP so a lot of what has been posted is confusing me a lot. But when I'm trying out various bits of code, I'm getting the following;
Warning: mysqli_query() expects at least 2 parameters, 1 given ...
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given
I've used each sample of code, but it seems like I'm mixing them now. Hmm.
You probably want something like this (database connection code and error handling not shown):
$id = intval($_GET['id']);
$result = mysqli_query("SELECT id, name FROM table WHERE id=$id");
$row = mysqli_fetch_assoc($result);
echo $row['id']." ".$row['name'];
About the posted code:
You never use $result.
Inside your switch, you are assigning $id to $_GET['id'], which results to using the include always, except when $_GET['id'] is 0.
You should pass the id value to your sql( by maintaining sql injection threat) and then you can get the values of the fetched by using fetch_assoc function of mysql(deprecated) or mysqli.
$id = $_GET['id'];
$result = mysqli_query($mysqli, "SELECT * FROM names where id='$id'");
$row = mysqli_fetch_array($result);
$row_id = $row['id'];
header("www.example.com/index.php?id=$row_id");
Warning! This is just a simple answer. There are many DANGERS of using this code as it is wide open for SQL injection attacks. Consider sanitation (eg. intval($_GET['id']). And header() function is used by assuming not header information is sent before this code (even space!).
You should use prepared statments. Here is an example using PDO
$stm = $pdo->prepare("SELECT name FROM table WHERE id=?");
$stm->execute(array($_GET['id']));
$name = $stm->fetchColumn();

MySQL - PHP Column Sum

I have searched all over the internet and have found various "helpful" tips about how to do a column sum with PHP and a MySQL table. The problem is that I can not get ANY of them to work.
Essentially I have a very simple database with 2 users. The table within the database is called users and each entry has a 'Name' and a 'Total Steps'. All I want to do is display the result of the total steps of each user and then a sum of their steps.
Here is my code:
<?php
$steps = mysql_query("SELECT SUM(Total_Steps) AS value_sum FROM users");
$row = mysql_fetch_assoc($steps);
$sum = $row['value_sum'];
?>
However, I get this error upon loading the page:
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /nfs/nfs4/home/msnether/apache/htdocs/st.php
Since I don't know PHP or MySQL very well yet, this is quite frustrating and I would appreciate any help.
Heres the basics step for you if your a beginner in using php and mysql..
FIRST : SET UP CONFIGURATION FOR DATABASE USER,PASS,HOST
$conn = mysql_connect('database_server','database_username','database_password');
SECOND : Execute a database connection.
mysql_select_db($conn,'database name');
THIRD : Create a Query(you may insert your query here)..
$sql= mysql_query("SELECT SUM(Total_Steps) AS value_sum FROM users");
FINAL : SHOWN RECORDS USING MYSQL FUNCTIONS LIKE..
while($row = mysql_fetch_array($sql)){
echo $row['dabatase_columnname'];
echo $row['database_columnname'];
}
If you "Do not know PHP and Mysql well" then, knowing or die(mysql_error()) will be a pretty useful tool for you in the future. Just add it here, and see what mysql will make you understand politely.
$steps = mysql_query("SELECT SUM(Total_Steps) AS value_sum FROM users") or die(mysql_error());

how can i get a field on a mysql table?

Im a php/mySQL newbie and am trying to get the hang of it. I have code to detect whether i get a username/password match, and now im trying to get the userid field so i can update the record. Heres what I have so far:
$sql = "SELECT username FROM users WHERE username='$username' AND password='$password'";
$result = $link->query($sql) or die(mysqli_error());
Using print_r($result) shows that there is an item, but im lost from here on out.
Try this.
$sql = "SELECT username FROM users WHERE username='$username' AND password='$password'";
$result = $link->query($sql) or die(mysqli_error());
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$userID= $row['username'] ;
// If you need other field as userID just change the sql and the index of $row according to that.
}
EDIT
If you want to get only one row.
if($result->num_rows==1)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
$userID = $row["username"];
}
Perhaps this will help. In any programming language, running an SQL query is going to consist of these steps:
Build the text of the SQL statement that you want to run.
(Optional) If your statement involves the use of parameters (or "placeholders"), prepare an array of the parameter-values that are to be substituted for each of them.
("Prepare" and...) "Run" the query, on some previously-opened "database connection." (In your example, "$link" must correspond to that connection.) This gives you a handle (you called it "$result") that corresponds to the zero-or-more rows that were returned by that query.
Now, use that handle to retrieve each of these rows, one at a time, until there are no more or until you're tired of doing it.
(Optional) Be neat and tidy and "close" the handle, thus indicating to the database system that it can discard all of the resources it was using to furnish those rows to you.
"Those, in simple terms, are the basic steps that every program in the known universe are going to go through," and if you now browse again through the PHP documentation, you'll see that there are functions that correspond to each of these steps. Browse through the chapters you've been reading and see if you can now match the up to the scenario I just described. HTH...

Categories