mysql php displays results but not inserting into database - php

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().

Related

PHP mysqli_query won't execute

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

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.

querying two database in php at a time

Whenever a user submits the registration form I am updating two database at a time. The first database easily gets updated but there is no effect in the second database. Below is my php code
<?php
$host="localhost";
$user="aru";
$password="arus";
$ur="asus";
$passord="asus";
$db="regster";
$dbn="nsltr";
$sq=mysql_connect($host,$user,$password) or die ('mysql connecction failed'.mysql_error());
mysql_select_db($db, $sq) or die('mysql cannot select database'.mysql_error());
$dbh2 = mysql_pconnect($host, $ur, $passord, true) or die ('mysql connecction failed'.mysql_error());
mysql_select_db($dbn, $dbh2) or die('mysql cannot select database'.mysql_error());
if(isset($_POST['btnSubmit1'])){
$fullName=htmlentities(mysql_real_escape_string($_POST['nme']));
$emailID=htmlentities(mysql_real_escape_string($_POST['emil']));
$bc=htmlentities(mysql_real_escape_string($_POST['bch']));
$bn=htmlentities(mysql_real_escape_string($_POST['bnc']));
$m=htmlentities(mysql_real_escape_string($_POST['mobe']));
$em=htmlentities(mysql_real_escape_string($_POST['empy']));
$a=htmlentities(mysql_real_escape_string($_POST['ofadrs']));
$me=htmlentities(mysql_real_escape_string($_POST['msge']));
$doj=date("Y-m-d");
$sql="insert into rgst values('$emailID', '$fullName', '$bc', '$bn', '$m', '$em', '$a', '$me', '$doj')";
$rndnm= uniqid();
$log="insert into nwsletter values('$emailID', '$fullName', '$rndnm')";
if((!(mysql_query($sql,$sq))) AND (!(mysql_query($log,$dbh2))) ){
echo '<script language="javascript">alert("Sorry!!! it seems you are already registered");</script>';
}
else{
echo '<script language="javascript">alert("Successfully registered.. Please check your mail address for password and other details");</script>';
}
}
?>
By the above code I am able to update register database but there is no change in nsltr database and also no error pops up after executing the codes. Please help, am new to php. Thanks in advance
It looks like your two databases are on the same server, and it looks like your database credentials grant access to both.
In this case you can use the same connection to update both data bases; simply qualify the database names in your SQL.
For example,
insert
into regstr.rgst
values ('$emailID', '$fullName', '$bc', '$bn', '$m', '$em', '$a', '$me', '$doj')
insert
into nsltr.nwsletter
values ('$emailID', '$fullName', '$rndnm')
You can even JOIN tables in different databases as long as they're on the same server and your username has access to both of them.
You should use the _num_rows() call right after running each query, to ensure it actually inserted the number of rows you were expecting.
I'll leave it to somebody else to whine at you about how freakin' dangerous it is to use the obsolete mysql_ API in a production application.
don't use mysql_ API, instead use mysqli_API. Below is your code using mysqli_ API. Hope it works for you
<?php
$host="localhost";
$user="aru";
$password="arus";
$ur="asus";
$passord="asus";
$db="regster";
$hst="localhost";
$ur="asus";
$passord="asus";
$dbn="nsltr";
$sq=mysqli_connect($host,$user,$password,$db);
if (mysqli_connect_errno($sq))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['btnSubmit1'])){
$fullName=htmlentities(mysql_real_escape_string($_POST['nme']));
$emailID=htmlentities(mysql_real_escape_string($_POST['emil']));
$bc=htmlentities(mysql_real_escape_string($_POST['bch']));
$bn=htmlentities(mysql_real_escape_string($_POST['bnc']));
$m=htmlentities(mysql_real_escape_string($_POST['mobe']));
$em=htmlentities(mysql_real_escape_string($_POST['empy']));
$a=htmlentities(mysql_real_escape_string($_POST['ofadrs']));
$me=htmlentities(mysql_real_escape_string($_POST['msge']));
$doj=date("Y-m-d");
$sql="insert into regster.rgst values ('$emailID', '$fullName', '$bc', '$bn', '$m', '$em', '$a', '$me', '$doj')";
$rndnm= uniqid();
$log="insert into nsltr.nwsletter values ('$emailID', '$fullName', '$rndnm')";
if((!(mysqli_query($sq,$sql)))){
echo '<script language="javascript">alert("Sorry!!! it seems you are already registered");
</script>';
}
else{
mysqli_close($sq);
$qq=mysqli_connect($hst,$ur,$passord,$dbn);
if (mysqli_connect_errno($qq))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
if((!(mysqli_query($qq,$log)))){
echo "Failed to connect to MySQL: " . mysqli_error($qq);
}
else{
echo '<script language="javascript">alert("Successfully registered.. Please check your mail address for password and other details");
</script>';
}
}
}
}
?>
Remember, you have to pass all the values for all the fields otherwise you might get "Column count doesn't match value count at row 1" error which will prevent from updating the databases

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