PHP mysqli_query won't execute - php

I'm trying to write my first basic PHP RESTful API - I managed to get it working on my local machine using MAMP. But when I uploaded to hosting server, it doesn't want to work.
Code below - I've added some ECHO's in there to make sure things are working along the way. It seems like we're all good up until the $result=mysqli_query.
<?php
//header('Content-type:application/json');
// Connect to db
$con = mysqli_connect("HOSTNAME","USER","PASSWORD","DATABASE");
echo "Database: ";
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
echo "<br><br>";
// Get value from url
$bid = $_GET['bid'];
echo "BID: ";
echo $bid;
echo "<br><br>";
// Define Query
$sql = "SELECT id, bandname, members, bio, songlist FROM bands WHERE id='$bid'";
echo "SQL Query: ";
echo $sql;
echo "<br><br>";
// Run Query
$result = mysqli_query($con, $sql);
echo "Result: ";
print_r($result);
echo "<br><br>";
// Put Query result into array
$result_array = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo "Result Array: ";
print_r($result_array);
echo "<br><br>";
// Encode array as JSON and output
echo "JSON: ";
echo json_encode($result_array);
?>
The url I'm entering is http://bandsly.com/api.php?bid=1 and this is the output I'm getting in the browser...
Database: Connected successfully
BID: 1
SQL Query: SELECT id, bandname, members, bio, songlist FROM bands WHERE id='1'
Result:
Result Array:
JSON: null
When I manually run the query SELECT id, bandname, members, bio, songlist FROM bands WHERE id='1' in the database (PHPmyadmin), it works fine and I get 1 row returned with the correct values.
The manual db query result:
(http://i.stack.imgur.com/d3ZPJ.png)
Any help would be most appreciated!!
*****EDIT*****
OK, i think i found the issue... My "successfully Connected" wasn't written correctly, and always came back looking good. It looks like after fixing that, i have db connection issues.
I'm going to go look up the db connection settings and try and fix that.
Thanks all for your help!

Your code seems to be ok on my localsystem http://www.awesomescreenshot.com/image/494275/c6c255cd6924d07196076b32489489de. There should be a connection problem . so you can do some try to check connection like
check the details in
// Connect to db
$con = mysqli_connect("HOSTNAME","USER","PASSWORD","DATABASE");
and then you can try to ping database
/* check connection */
if ($con->connect_errno) {
printf("Connect failed: %s\n", $con->connect_error);
exit();
}
/* check if server is alive */
if ($con->ping()) {
printf ("Our connection is ok!\n");
} else {
printf ("Error: %s\n", $con->error);
}

Your all code is correct, I have tested in my local just change your
HOSTNAME like "localhost", USER like "root", PASSWORD like "your password", DATABASE like "YOUR DATABASE NAME".
$con = mysqli_connect("HOSTNAME","USER","PASSWORD","DATABASE");
please, visit http://php.net/manual/en/function.mysqli-connect.php

Related

Selecting * from table returns nothing

I wrote this php script that allows me to fetch all the rows in a table in my MySQL database.
I have put the echo "1", etc. to see whether it gets to the code at the very end. The output proves it does. However, it does not output anything when echoing json_encode($resultsArray), which I can't seem to figure out why.
Code:
// Create connection
$connection = mysqli_connect("localhost", "xxx", "xxx");
// Check connection
if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } else { echo "0"; }
// select database
if (!mysqli_select_db($connection, "myDB")) { die('Unable to connect to database. '. mysqli_connect_error()); } else { echo "1"; }
$sql = "select * from myTable";
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));;
echo "3";
$resultsArray = array();
while($row = mysqli_fetch_assoc($result)) {
// convert to array
$resultsArray[] = $row;
}
echo "4";
// return array w/ contents
echo json_encode($resultsArray);
echo "5";
Output:
01345
I figured, it is not about the json_encode, because I can also try to echo sth. like $result['id'] inside the while loop and it just won't do anything.
For testing, I went into the database using Terminal. I can do select * from myTable without any issues.
Any idea?
After around 20hrs of debugging, I figured out the issue.
As I stated in my question, the code used to work a few hours before posting this question and then suddenly stopped working. #MichaelBerkowski confirmed that the code is functional.
I remembered that at some point, I altered my columns to have a default value of an empty string - I declared them as follows: columnName VARCHAR(50) NOT NULL DEFAULT ''.
I now found that replicating the table and leaving out the NOT NULL DEFAULT '' part makes json_encode() work again, so apparently there's an issue with that.
Thanks to everybody for trying anyway!

mysql php displays results but not inserting into database

I stripped down query for only one insert
<?php
session_start();
include 'cstring.php';
$title="";
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
$title=$_POST['title'];
$query=mysqli_query($con,"insert into blogpages(blogpagetitle) values('".$title."')");
if($query){
$bloga="sucessfully added a new blog";
echo $bloga;
}
else {
echo mysqli_error($con); // if using mysqli do not use mysql in between
}
}
mysqli_close($con);
?>
is there something wong in this code that it doesnt insert into mysql
table structure
1.bpid int(50)--------------null-no default-none autoincrement
2.blogpagetitle------------varchar(255) utf16_general_ci
3.datemade-------------timestamp current time stamp
4.blogpagedescription---------text utf16_general_ci
5.blogbody----------------longtext utf16_general_ci
6.blogpageextended------------ text utf16_general_ci
TIP
Sanitize variables, Use mysqli_real_escape_string()
When you are not able to debug your code, echo every possible stuff and die the rest code.
For example here, echo if there is error in DB connection, echo the query to see if it is correct, echo the result of query execution, echo if there is some error!
You should be using echo mysqli_error($con) to get the error message rather than mysql_error().

So i'm trying to have it check to see if the steamid64 all ready exists before inserting but it just inserts any way?

So i'm trying to have it check to see if the steamid64 all ready exists before inserting but it just inserts any way?
i'm not good with PHP here.
<?php
$con=mysqli_connect("localhost","user","pass","Gmod");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$SteamID64 = mysqli_real_escape_string($con, $_POST['SteamID64']);
$enable = mysqli_real_escape_string($con, $_POST['enable']);
$sql="SELECT * FROM Loading (SteamID64, enable) WHERE SteamID64='$SteamID64'";
if(mysql_num_rows($sql)>=1) {
echo'<center>The music is already disabled!</center>';
}
else {
$sql="INSERT INTO Loading (SteamID64, enable)
VALUES ('$SteamID64', '$enable')";
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "<center>The music will not play when you connect.</center>";
mysqli_close($con);
?>
i got this off some forums and w3schools.com
and edited it.
Ok so i did this but its still just inserting the data?
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
$con=mysqli_connect("localhost","root","server","Gmod");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$SteamID64 = mysqli_real_escape_string($con, $_POST['SteamID64']);
$enable = mysqli_real_escape_string($con, $_POST['enable']);
mysqli_query($con,"SELECT * FROM Loading WHERE SteamID64='$SteamID64'");
if(mysqli_num_rows(mysqli_query)>=1) {
echo'<center>The music is already disabled!</center>';
}
else {
mysqli_query($con,"INSERT INTO Loading (SteamID64, enable)
VALUES ('$SteamID64', '$enable')");
}
echo "<center>The music will not play when you connect.</center>";
mysqli_close($con);
?>
Apart from the fact that you cannot mix mysql_* and mysqli_* functions like that (pick one, mysqli_* and stick to that), you have an error in your sql:
SELECT * FROM Loading (SteamID64, enable) WHERE SteamID64='$SteamID64'
^^^^^^^^^^^^^^^^^^^ this should not be here
You need to change that to:
SELECT * FROM Loading WHERE SteamID64='$SteamID64'
You can have mysqli throw exceptions so that it tells you exactly what went wrong when it goes wrong. Just add this to the top of your script:
mysqli_report(MYSQLI_REPORT_STRICT);
Another problem you have, is that the execution of your second query should be inside the else part of the previous condition.
And as #FabrícioMatté already mentioned, you actually need to execute your query using mysqli_query(), just setting the string does not do anything.

No Database Selected Php

This is a somewhat simple task, I am trying to compare a username to that in the database. I am testing it out in a single php file before I do it properly. My code is below. Basically I have a user, which is in the database and I am checking if it is in there.
<?php
$db_connect = mysql_connect("127.0.0.1", "root", "anwesha01", "mis");
//Check if connection worked.
if(!$db_connect)
{
die("Unable to connect to database: " . mysql_error());
}
//For testing purposes only.
else
{
echo "Database connect success!";
}
$user = "alj001";
$query = "SELECT Username FROM `user` WHERE `Username` = '".$user."'";
//What is being passed through the database.
echo "<p><b>This is what is being queried:</b> " . $query;
//Result
if (mysql_query($query, $db_connect))
{
echo "<br> Query worked!";
}
else
{
echo "<p><b>MySQL error: </b><br>". mysql_error();
}
?>
The result I get is:
Database connect success!
This is what is being queried: SELECT Username FROM user WHERE Username = 'alj001'
MySQL error: No database selected
First I had my mysql_query without the $db_connect as it is above, but I put it in and I still get "no database selected".
Ive looked at the w3c schools for the mysql_query function, I believe I have done everything correctly. http://www.w3schools.com/php/func_mysql_query.asp
Because you haven't called mysql_select_db. Note that the 4th parameter to mysql_connect is not what you think it is.
That said, you really should be using PDO or mysqli, not the plain mysql_ functions, since they're deprecated.

mysqli_insert_id() not working?

I'm getting quite angry over this, I don't know how can this simple situation be so complicated and not work.
Basically:
$lastInsertId = mysqli_insert_id($query);
echo $lastInsertId;
returns NULL
my $query runs fine, inserts perfectly. Anyone knows why I'm not getting the last insert id?
What is $query? You have to pass the mysqli link as parameter ($link = mysqli_connect(...)). Maybe your $query is the result of mysqli_query or something else.
mixed mysqli::mysqli_insert_id ( mysqli $link )
Manual: http://php.net/mysqli_insert_id
//you follow the folow the bellow code
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
// Print auto-generated id//
//NOTE: $con link should be in ()
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>

Categories