php is not connecting with mysql - php

I want to perform a query on a database with genomic information.
This is part of the php code:
$db = mysqli_connect($servername,$username,$password,$database)
$fields = "name, chrom, strand, txStart, txEnd, exonCount, name2";
$query = "SELECT $fields FROM $table WHERE name2 LIKE '%$gene%';";
$result = mysqli_query($db,$query);
$items = mysqli_affected_rows($result);
if ($items == 0)
{
print_error("The gene $gene is not found in the RefSeq database");
}
else
{
$transcripts = $items;
echo "<html>\n";
echo "<head>\n";
echo "<title> Catalogue web server </title>\n";
echo "<link href=\"styles.css\" rel=\"stylesheet\">\n";
echo "</head>\n";
echo "<body>\n";
echo "<h1>Catalogue output ($gene)</h1>\n";
echo "<table>\n";
echo "<tr><th>GENE</th><th>TRANSCRIPTS</th><th>CHR</th><th>STRAND</th><th>POS1</th><th>POS2</th><th>EXONS</th>\n";
for ($i = 0; $i<$items; $i++)
{
$row = mysqli_fetch_array($result);
$name2 = $row["name2"];
$name = $row["name"];
$chrom = $row["chrom"];
$strand = $row["strand"];
$txStart = $row["txStart"];
$txEnd = $row["txEnd"];
$exonCount = $row["exonCount"];
echo "<tr><td>$name2</td><td>$name</td><td>$chrom</td><td>$strand</td><td>$txStart</td><td>$txEnd</td><td>$exonCount</td>\n";
}
echo"</table><br><br>\n";
}
However, when I submit the query from html localhost, I´m always getting the error message:
The gene is not in the database
When I know it is.
Any help finding the error would be appreciated it.
ALSO: $servername, $username, $password and $database are correct, checked several times
I don´t mind about mysql injections as I´m not publishing this web

Try instead with:
$items = mysqli_num_rows($result);
The mysqli_affected_rows is used after insert, update, replace or delete queries.

Related

PHP mysqli_query() expects parameter 1 to be mysqli, null given in Confusing help needed

I am trying to store IP's in a MySQL database and I had a few problems with it which i was able to fix but i keep getting 1 error for people that trying to get onto my website. So when someone gets on my website their IP is displayed with a time stamp but it only works when I connect to my website. When I got my friend to go onto my website he got an error saying why u no query? which helps me find out where the problem is. Now the problem is that I have been trying to solve this issue for the past 2 hours with no luck :(
Screenshot of my screen: My screen
Screenshot of my friends screen: Friends screen
<html>
<head>
<title>Your IP!</title>
</head>
<body>
<?php
$db_host = '127.0.0.1';
$db_user = '***************';
$db_pwd = '*************';
$db = '***************';
// Find their IP and tell them what it is.
$con=mysqli_connect($db_host, $db_user, $db_pwd);
if (getenv('HTTP_X_FORWARDED_FOR')) {
$pip = getenv('HTTP_X_FORWARDED_FOR');
$ip = getenv('REMOTE_ADDR');
echo "Your Proxy IP is: ".$pip."(via ".$ip.")";
} else {
$ip = getenv('REMOTE_ADDR');
echo "Your IP is: ".$ip;
}
echo "<br /><br />";
// Try to select the database.
if(!mysqli_select_db($con, $db)) {
// die("why u no use db? ".mysql_error());
die("why u no use db?");
}
// Try to perform query.
// This is a function so it may easily be called multiple times.
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die("why u no query?");
}
return $result; // Give back result.
}
// Try to see if they are in the database already,
// and if not, then add them.
$result = do_query("select ip from ips where ip='".$ip."'");
$rows = mysqli_num_rows($result);
if($rows == 0) {
do_query("insert into ips (ip) values ('".$ip."')");
}
// Now, display the table.
$result = do_query("select * from ips");
$cols = mysqli_num_fields($result);
echo "<table cellpadding=\"5\" bgcolor=\"#7F7F7F\"><tr>";
for($i = 0; $i < $cols; $i++) {
echo "<td>".mysqli_fetch_field($result)->name."</td>";
}
echo "</tr>";
while($row = mysqli_fetch_row($result)) {
echo "<tr>";
for($i = 0; $i < $cols; $i++) {
if($row[$i] == $ip) { // bold their IP.
echo "<td><b>".$row[$i]."</b></td>";
} else {
echo "<td>".$row[$i]."</td>";
}
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
So first I changed
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die("why u no query?");
to
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die(mysqli_error($con));
Which showed me the error which was Duplicate entry '0' for key 'PRIMARY' and the problem was that I did not set AUTO_INCREMENT on the Primary key.

Not able to insert the data from url to database in php

final.php
Here I am trying to get the data from the url using GET method and trying to insert into the database. I was able to insert the data for first few rows after that the data is not inserted. Can anyone help me regarding this?
when I try to run the url: www.myii.com/app/final.php?name=123&glucose=3232...
the data is not inserting.
<?php
include("query_connect.php");
$name = $_GET['name'];
$glucose = $_GET['glucose'];
$temp = $_GET['temp'];
$battery = $_GET['battery'];
$tgs_a = $_GET['tgs_a'];
$tgs_g = $_GET['tgs_g'];
$heartrate = $_GET['heartrate'];
$spo2 = $_GET['spo2'];
$rr = $_GET['rr'];
$hb = $_GET['hb'];
$ina22 = $_GET['ina22'];
$accucheck = $_GET['accucheck'];
$isactive = $_GET['isactive'];
$address = $_GET['address'];
$deviceno = $_GET['deviceno'];
$sql_insert = "insert into query (name,glucose,temp,battery,tgs_a,tgs_g,heartrate,spo2,rr,hb,ina22,accucheck,isactive,address,deviceno) values ('$name','$glucose','$temp',$battery','$tgs_a','$tgs_g','$heartrate','$spo2','$rr','$hb','$ina22','$accucheck','$isactive','$address','$deviceno')";
mysqli_query($sql_insert);
if($sql_insert)
{
echo "Saving succeed";
//echo $date_time;
}
else{
echo "Error occured";
}
?>
Query_connect.php
This is my database config php file.
<?php
$user = "m33root";
$password = "me3i434";
$host = "localhost";
$connection = mysqli_connect($host,$user,$password);
$select = mysqli_select_db('miiyy',$connection);
if($connection)
{
echo "connection succesfull<br>";
}
else {
echo "Error";
}
?>
Make sure that all columns can contain NULL so that not filled fields will stay NULL instead of throwing an error.
Try below to see mysql error:
mysql_query($sql_insert);
echo mysql_error()
Try these
In SQL
Change the table name of query to some other name. Because "query" is reserved in SQL
In code
if (!mysqli_query($con,$sql_insert ))
{
echo("Error description: " . mysqli_error($con));
}
else
{
echo "Success";
}
Use mysqli_error() function

Returning a whole MYSQL table data on PHP

I found this code once...
$sql_select = "SELECT * FROM users";
$rs_stuff = select($sql_select);
while ($res = mysql_fetch_assoc($rs_stuff)) {
echo ($res("Name")."<br />");
}
It works well, it returns all names found in "Name" col, the problem is I want it to make to return all data in that table, like if I just typed "SELECT * FROM users" on mysql, I don't understand much of PHP, I tried to do this:
echo("<br />\n".$res);
But when trying to run this on the page, I just got a empty blank with "Array" written on it...
Is it possible to do this without putting the col names in the php?
(Sorry about my English, it is not my main language.)
This happens because $res is a Array
use:
print_r($res);
or if you want a better view of it:
echo '<pre>';
print_r($res);
echo '</pre>';
OR
you can use:
echo ($res["Name"]."<br />");
also, on this second option, watch out for multidimensional arrays. Your $res might be one. In which case it will be:
echo ($res[0]["Name"]."<br />");
if you have only one result. I suggest you go with the first choice and see how your $res looks like before echoing strings ;)
Either way, please find a good PHP tutorial as it is CLEAR that you lack basic knowledge of how to use and manipulate PHP code.
Hope it helps! :D
$sql_select = "SELECT * FROM users";
$rs_stuff = select($sql_select);
echo '<table>';//create the table
while ($res = mysql_fetch_assoc($rs_stuff)) {
echo '<tr><td>'.$res['name'].'</td></tr>';
}
If you learning learn mysqli_ or PDO their is no point in learning mysql as they are depriciated.
Try this
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
print_r($row)
}
} else {
echo "0 results";
}
$conn->close();
?>
please put all your rows in an array and then print.
$sql_select = "SELECT * FROM users";
$rs_stuff = select($sql_select);
$arr = array();
while ($res = mysql_fetch_assoc($rs_stuff)) {
$arr[] = $res["Name"];
}
echo '<pre>';
print_r($arr);
echo '<pre>';
Try with this :
foreach($res as $key => $value) {
print $res[$key] . ' => ' . $value;
}
hope that helps :)
It hink this will help:
$sql_select = "SELECT * FROM users";
$rs_stuff = mysql_query($sql_select);
while ($res = mysql_fetch_assoc($rs_stuff)) {
foreach($res as $key => $value) {
echo $key.': '.$value."<br />\n";
}
echo "<br />\n";
}
Loop trough the array of values in the columns and echo out the cells value in the column.
I think this will look like this:
Name: John<br />
Usernmae: johndoe<br />
Age: 36<br />
<br />
Name: Christian<br />
Username: admin<br />
Age: 46<br />
<br />
Don't use echo to print out an array. When you use echo PHP wants to convert an array to a string. If you only want to get the arrays values use print_r. Or use this function:
function convertArraytoString($array) {
foreach($array as $key => $value) {
$return .= $key.': '.$value."<br />\n";
}
return $return;
}
Than you can convert to the array via echo convertArraytoString($res);

Passing JSON to Array in PHP

I'm working on a filter in which results are filtered right away, I'm wondering if that may be the cause of the problem so I thought I would ask and see if anyone could give me a pointer on how to proceed.
<script>
var services = [
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "###";
$username = "###";
$dbname = "###";
//These variable values need to be changed by you before deploying
$password = "###";
$usertable = "###";
$url = "permalink";
$title = "Address";
$amount = "rent";
$id = "id";
$status = "Beds";
$nonprofit = "Address";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("He's dead Jim");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result) {
while($row = mysql_fetch_array($result)) {
$url = $row["$url"];
$title = $row["$title"];
$amount = $row["$amount"];
$id = $row["$id"];
$status = $row["$status"];
$nonprofit = $row["$nonprofit"];
echo '{"permalink": "';
echo "{$url}";
echo '",';
echo '"title": "';
echo "{$title}";
echo '",';
echo '"amount":';
echo "{$amount}";
echo ',';
echo '"id": "';
echo "{$id}";
echo '",';
echo '"status": "';
echo "{$status}";
echo '",';
echo '"address": "';
echo "{$address}";
echo '",';
echo '},';
}
}
?>
]
//]]>
</script>
<script id="template" type="text/html">
<a title="{{title}}" href="{{permalink}}">
<div class="fs_box hide-for-small-down">
<div class="fs_left">
<span class="fs_head">{{title}}</span>
<span class="fs_id"><img src="images/{{id}}.jpg" width="75%" height="75%" onError="this.onerror=null;this.src='images/logo.png';"></span>
<span class="fs_status">{{status}}</span>
<span class="fs_disc">{{address}}</span>
</div>
<div class="fs_price">${{amount}}+</div>
<div class="clear"></div>
</div>
</a>
</script>
I'm expecting it to produce a bunch of results that then are filtered criteria which are elsewhere in the page.
When I try it currently just as a php code it outputs fine. However, when I try it in the php file that this should go in it produces nothing. Or does it dislike being in a script?
Thanks for any help!
You can use json_decode and json_encode to turn an array to json and json back to an array.
Also someone will probably mention that you should not be using the mysql_* functions in PHP as they are depreciated.
Something like this:
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "###";
$username = "###";
$dbname = "###";
//These variable values need to be changed by you before deploying
$password = "###";
$usertable = "###";
$url = "permalink";
$title = "Address";
$amount = "rent";
$id = "id";
$status = "Beds";
$nonprofit = "Address";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("He's dead Jim");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result) {
$results = array()
while($row = mysql_fetch_array($result)) {
$results[] = $row;
}
$json = json_encode($results);
}
?>
]
<script>
var services = <?php echo $json; ?>;
</script>
This would give you a json object to use to render in your script.
What extension is the file you are saving?
If it's not .php or an extension set to render php, then you'll just have the code show up as test.
You might want to pull out the "die" statement after the db connect. This looks like you are running php in a .js file so you probably want the entire file to write out rather than stop because you couldn't connect to the database (or at least give 0 results, maybe a warning)

Display "x results found" or "no results found" when returning MySQL Query results

The search function works like a charm, but I'm not sure how to add certain "extras" to it. When there are results to display, I would also like it to say:
"Your search returned x results."
Followed by the results.
When there are no results to display, I would like it to say:
"Your search returned no results. Please try again."
And when the user does not input anything into the search form, I would like it to say:
"You did not enter a search term."
I'm a PHP beginner, and I'm not sure how to implement this into my current code; I've tried a bunch of different ways, and it either gives me errors or returns a blank page when there are no results.
Any direction or help would be great. Thank you.
Here is my current code:
<?php
//STEP 1 Connect To Database
$connect = mysql_connect("localhost","tarb89_admin","leccums");
if (!$connect)
{
die("MySQL could not connect!");
}
$DB = mysql_select_db('tarb89_characters');
if(!$DB)
{
die("MySQL could not select Database!");
}
//STEP 2 Check Valid Information
if(isset($_GET['search']))
{
//STEP 3 Declair Variables
$Search = $_GET['search'];
$result = mysql_query("SELECT * FROM characters WHERE name LIKE '%$Search%' ");
while($row = mysql_fetch_assoc($result))
{
$name = $row['name'];
$id = $row['id'];
$breed = $row['breed'];
$gender = $row['gender'];
$genetics = $row['genetics'];
$profile = $row['profile'];
$player = $row['player'];
$color = $row['color'];
$markings = $row['markings'];
$traits = $row['traits'];
$defects = $row['defects'];
$extras = $row['extras'];
echo " <h3>$name</h3>
<table width='700px' cellpadding='5' cellspacing='0'>
<tr>
<td><p>
<b>ID Number: </b>$id<br>
<b>Breed: </b>$breed<br>
<b>Gender: </b>$gender<br>
<b>Genetics: </b>$genetics<br>
<b>Profile:</b> <a href='$profile'>$profile</a><br>
<b>Player:</b> $player</p></td>
<td><p>
<b>Color:</b> $color<br>
<b>Markings:</b> $markings<br>
<b>Traits:</b> $traits<br>
<b>Defects:</b> $defects<br>
<b>Extras:</b> $extras</p></td>
</table>";
}
}
?>
Use mysql_num_rows() to return number of rows
if($search!="") {
// Your Query
$num = mysql_num_rows($result);
if($num >= 1)
{
echo "Your search returned $num results";
// your code
}
else
{
echo "Your search returned no results. Please try again";
}
} else {
echo "You did not enter a search term";
}
YOUR CODE
if(isset($_GET['search']))
{
//STEP 3 Declair Variables
$Search = $_GET['search'];
$result = mysql_query("SELECT * FROM characters WHERE name LIKE '%$Search%' ");
$num = mysql_num_rows($result);
if($num >= 1)
{
echo "Your search returned $num results";
while($row = mysql_fetch_assoc($result))
{
$name = $row['name'];
$id = $row['id'];
$breed = $row['breed'];
$gender = $row['gender'];
$genetics = $row['genetics'];
$profile = $row['profile'];
$player = $row['player'];
$color = $row['color'];
$markings = $row['markings'];
$traits = $row['traits'];
$defects = $row['defects'];
$extras = $row['extras'];
echo " <h3>$name</h3>
<table width='700px' cellpadding='5' cellspacing='0'>
<tr>
<td><p>
<b>ID Number: </b>$id<br>
<b>Breed: </b>$breed<br>
<b>Gender: </b>$gender<br>
<b>Genetics: </b>$genetics<br>
<b>Profile:</b> <a href='$profile'>$profile</a><br>
<b>Player:</b> $player</p></td>
<td><p>
<b>Color:</b> $color<br>
<b>Markings:</b> $markings<br>
<b>Traits:</b> $traits<br>
<b>Defects:</b> $defects<br>
<b>Extras:</b> $extras</p></td>
</table>";
}
}
else
{
echo "Your search returned no results. Please try again";
}
} else {
echo "You did not enter a search term";
}
Note: mysql_* functions are deprecated, Move on mysqli_* functions asap

Categories