Recently I've bought webhosting at names.co.uk and I'm trying to set up something simple which will display the name from a table named Team if the id = 1.
This is my code
<?php
$q = "SELECT * FROM `Team` WHERE id =1";
$result = mysql_query($q);
echo '<br />Query is send';
echo '<br />Result is true';
$row = mysql_fetch_array($result);
echo '<br />tryed fetching row';
if ($row === FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
echo( mysql_error());
}
echo $name;
?>
This is the output:
Query is send Result is true tryed fetching rowNo such file or
directory
UPDATE:
I have changed to msqli:
$q = "SELECT * FROM `Team` WHERE id =1";
$result = mysqli_query($q);
echo '<br />Query is send';
echo '<br />Result is true';
$row = mysqli_fetch_array($result);
echo '<br />tryed fetching row';
if ($row !== FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
echo( mysqli_error());
}
echo $name;
and now I'm getting this output:
Query is send Result is true tryed fetching row $row is not false.
$name now is ""
You need to fist establish a connection. For example: $connection = mysqli_connect($servername, $username, $password);.
See this link on how to use MySQLi: https://www.w3schools.com/PHP/php_mysql_connect.asp (but note that w3schools is a bad resource, with outdated information and bad practices - I'm only linking to it because this tutorial is basic and clear).
Be sure to check later, if you still haven't, on how to properly sanitize your queries. See this, for example: How can I prevent SQL injection in PHP?
Use function:
$result = mysqli_query($q);
mysql_query() have been deprecated in PHP7 onwards.
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 beginner learning PHP and MySQL and have gotten to chapter 5 of Head First PHP & MySQL and am attempting a self made project in which I created a database and a index.php page where I can see the results printed out. When I go to my index.php page I see the HTML title but the PHP code is not printing out my submissions. I have to assume my code syntax is correct or I would end up with a blank page. Can someone please tell me what I have coded wrong to wind up with no output?
<?php
$dbc = mysqli_connect(localhost, root, root, itmyfamily);
$query = "SELECT * FROM itsmyfamily ORDER BY last_name ASC, first_name DESC, date ASC";
$data = mysqli_query($dbc, $query);
$i = 0;
while ($row = mysqli_fetch_array($data))
{
if ($i == 0)
{
echo '<strong>First Name:</strong> ' . $row['first_name'] . ' <br />';
echo '<strong>Last Name:</strong> ' . $row['last_name'] . ' <br />';
echo '<strong>Spouse Name:</strong> ' . $row['spouse_name'] . ' <br />';
echo '<strong>Email:</strong> ' . $row['email'] . ' <br />';
}
else
{
echo 'There is no info in the database';
}
$i++;
}
mysqli_close($dbc);
Set this on top of the source code to display errors.
<?php error_reporting( E_ALL ); ?>
Or set display_erros in php.ini as follows:
display_errors = On
error_reporting = E_ALL | E_STRICT
Also try to replace your source code with following,
<?php
//Establish connection with database
$dbc = mysqli_connect(localhost,root,root,itmyfamily);
//Order the data to be retrieved
$query = "SELECT * FROM itsmyfamily ORDER BY last_name ASC, first_name DESC, date ASC";
//Execute the connect command and the query
$data = mysqli_query($dbc,$query);
while ($row = mysqli_fetch_array($data)) {
//Loop through the array of family submissions, formatting it as html
$i = 0;
//Display family submissions
if ($i == 0) {
echo '<strong>First Name:</strong> ' .$row['first_name']. ' <br />';
echo '<strong>Last Name:</strong> ' .$row['last_name']. ' <br />';
echo '<strong>Spouse Name:</strong> ' .$row['spouse_name']. ' <br />';
echo '<strong>Email:</strong> ' .$row['email']. ' <br />';
}
else{
echo 'There is no info in the database';
}
$i++;
}
mysqli_close($dbc);
?>
If you can write it this way, I think you don't even need the $i.
$result = mysql_query("SELECT id, first_name FROM mytable");
if($result){
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
printf("ID: %s Name: %s", $row["id"], $row["first_name"]);
}
}
else
echo 'There is no info in the database';
Read here for more information about PHP mysql_fetch_array http://www.php.net/mysql_fetch_array
Read here for more information about iterations. http://webcheatsheet.com/php/loops.php
Please note that the method you have used is deprecated from PHP 5.5.0. So I suggest you consider mysqli or PDO. Examples can be found in below PHP manual links
http://www.php.net/manual/en/mysqli.query.php
http://www.php.net/manual/en/pdo.query.php
I'm trying to echo out a specific value, but whenever I run the code- all I get is
nothing.
My code is here:
$studentname = mysql_query("SELECT * FROM $alias WHERE FBID=$user") or die ('Error: '.mysql_error ());
while($row = mysql_fetch_array($studentname))
{
$queried_name = $row['Name'];
echo 'Name: ' . $queried_name;
}
$name IS your resource handler because of this...
$name = mysql_query("SELECT * FROM $alias WHERE FBID=$user") ...
and the error you received is because you tried to echo the resource handler, inside your loop
echo ( 'Name: '.$name );
I understand the confusion, and I would suggest that you name your variables accordingly to avoid this. I would always name my resource handler with a prefix of $rs to make it clear that it is a resource.
$name is the resource handle for the MySQL connection. Use a different variable, and echo inside the loop
$name = mysql_query("SELECT * FROM $alias WHERE FBID=$user") or die ('Error: '.mysql_error ());
while($row = mysql_fetch_array($name))
{
$queried_name = $row['name'];
echo 'Name: ' . $queried_name;
//optionally just do
//echo 'Name: ' . $row['name'];
}
I'm trying to populate a dropdown list in my web page from a mysql database table which has only one column (pathology_id). I know there is test data in there but the best I can do is populate the box with the field name, not the row values. The code I have thus far is below, can anyone suggest how to get more than just the column name? Thanks in advance.
<?php $con = mysql_connect("localhost","dname","dbpass");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
$fields = mysql_list_fields("dbname","PATHOLOGY",$con);
$columns = mysql_num_fields($fields);
echo "<form action = newcase.php method = POST><select name = Field>";
for($i = 0; $i < $columns ; $i++)
{
echo "<option value = $i>";
echo mysql_field_name($columns , $i);
}
echo "</select></form>";
if(!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
echo "1 record added";
}
mysql_close($con) ?>
Try this:
<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname = 'fox';
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
From PHP: mysql_query().
mysql_list_fields just returns information about a given table, NOT the data contained.
Select option should has close tag.
echo '<form action="newcase.php" method="POST"><select name"="Field">';
for($i = 0; $i < $columns ; $i++)
{
echo '<option value="' . $i . '">';
echo mysql_field_name($columns , $i);
echo '</option>';
}
echo '</select></form>';
Heres my code
<?php
session_start();
include('config.php');
if(isset($_GET['search_word']))
{
// echo $_GET['search_word'] . '<br />'; // debugging
$search_word = $_GET['search_word'];
$search_word = mysql_escape_string($search_word);
$search_word_fix = str_replace(" ","%",$search_word);
$query = "SELECT * FROM article WHERE article_title LIKE '%" . $search_word . "%' AND article_live = '1' ORDER BY article_id DESC";
// echo $query . '<br />'; // debugging
$sql = mysql_query($query);
$count = mysql_num_rows($sql);
// echo $count . '<br />'; // debugging
// echo mysql_num_rows($sql) . '<br />'; // debugging
if($count > 0)
{
while($row=mysql_fetch_array($sql))
{
$msg=$row['article_title'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $msg);
echo $final_msg;
}
}
else
{
echo "No Results";
}
}?>
Can anyone see an issue with it? I cant pick out what is not working with this script and ive been staring at it for a while. It never makes it to the WHILE loop only the "No Results" and the count returns blank when i uncomment my debugging.
Count returning blank means your query failed for some reason.
Are you connecting to the db properly? Try using mysql_error() right after your query:
$error_msg = mysql_error();
Use mysql_real_escape_string() instead of mysql_escape_string() - it respects the character set so that you don't have UTF8 issues
If you're using this publicly, you may want to learn about using binds to eliminate the possibility of SQL injection via a library like PDO.
Here's a pretty good tutorial/introduction to PDO explaining why it's important!