an If satement that is stopping me from writing to database - php

I was able to succsess fully write to a database. The problem was the same information kept getting written so I created a json file that stored the id of each object and wrote some php to check if the id was already in the file and if not it would write the whole object to a database and just write the id to the json file. The checking of the json object and writing to the json file work but not the writing to my database. Any help would be much appreciated
Here is the code. From the beginning of the if statement to fclose is the code i added to perform the check that now stops me from writing to a databse.
<?php
$host="xxxxxxxxxxxx"; // Host name
$username="xxxxxxxxxxxx"; // Mysql username
$password="xxxxxxxxxxxxxx"; // Mysql password
$db_name="xxxxxxxxxxxxx"; // Database name
$name= $_POST['postname'];
$user= $_POST['postuser'];
$status= $_POST['poststatus'];
$id= $_POST['postid'];
$img= $_POST['postimg'];
//$id= $_POST['postid'];
//file_put_contents("index.json", $id, FILE_APPEND);
$list = file_get_contents('index.json');
$json = json_decode($list, true);
if (in_array($id, $json)) {
echo "already exists";
} else{
array_push($json, $id);
$file ="index.json";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, json_encode($json));
fclose($fh);
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$db_insert = mysql_query("INSERT INTO tweet(name, user, status, Img, tweetid) VALUES ('$name', '$user', '$status', '$img', '$id')");
}
?>

Just declare the ID row as UNIQUE in MySQL.
ALTER IGNORE TABLE tweet ADD UNIQUE (tweetid);

Related

My PHP page is not working. It is completely blank

I am working on a site to share names of songs, and I have made a recommendation form that I include in every page. This recommendation form is in HTML and leads to a PHP action page, where the information received is added to a SQL table. Here is the code:
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="MYPASSWORD"; // Mysql password
$db_name="DB NAME"; // Database name
$tbl_name="songshare"; // Table name
// Connect to server and select databse.
$link = mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_select_db($link, "$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$song=$_POST['song'];
$album=$_POST['album'];
$artist=$_POST['artist'];
$linkitunes=$_POST['linkitunes'];
$artwork=$_POST['albumPic'];
// To protect MySQL injection (more detail about MySQL injection)
$song = stripslashes($song);
$album = stripslashes($album);
$artist = stripslashes($artist);
$song = mysqli_real_escape_string($link, $song);
$album = mysqli_real_escape_string($link, $album);
$artist = mysqli_real_escape_string($link, $artist);
$sql="SELECT * FROM $tbl_name WHERE song='$song'";
$result=mysqli_query($link, $sql);
if ($result->num_rows){
echo "Song already taken" . "<br />";
echo "<a href='/music.php'>music</a>";
exit();
}
$sql="INSERT INTO recommendation (user_id, artist, song, album, artwork, linkitunes)";
$sql = $sql . " VALUES ('$_SESSION['user_id']', '$artist', '$song', '$album'. '$artwork'. '$linkitunes');";
$result=mysqli_query($link, $sql);
if(!$result) {
echo "Recommendation failed" . "<br />";
echo $sql;
} else {
print "$song, $artist, $album";
}
ob_end_flush();
?>
I have checked that every username, password, link is correct and valid. My server does, in fact, run PHP. It doesn't seem to me like the PHP code is even running though.
Thank you so much in advance.
-Cameron
Turn on error reporting by adding this on top of page:
ini_set("display_errors",true);
and change this line:
$link = mysqli_connect("$host", "$username", "$password")
to
$link = mysqli_connect($host, $username, $password,$db_name);
Please have a look how to work with mysqli
Instead of '$album'. '$artwork'. '$linkitunes' Do: '$album', '$artwork', '$linkitunes', while saving data.
Try this :-
$sql = $sql . " VALUES ('".$_SESSION['user_id']."', '$artist', '$song', '$album', '$artwork', '$linkitunes')";
instead of
$sql = $sql . " VALUES ('$_SESSION['user_id']', '$artist', '$song', '$album'. '$artwork'. '$linkitunes');";
You should check the version of local server you are working with. If you are working with a higher of local server and you php was written in a lower version it throws a blank page.

Json returns Null instead some datas

I'm trying to display in a TextView the text in this page: http://www.oscarilfilm.com/oscar/
using json, php and mysql. I created a json.php to fetch data from db and encode the data in json using this:
<?php
$host="XXXXX"; //replace with database hostname
$username="XXXXX"; //replace with database username
$password="XXXXX"; //replace with database password
$db_name="XXXXXX"; //replace with database name
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from emp_info";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['emp_info'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
And it goes. But when i try change the query to display that post i get this: http://www.oscarilfilm.com/newjson.php and exactly this for OSCAR page: {"id":"39","post_title":"Oscar","post_content":null}
but it's impossible! it can't be null! there is some content! Why? I'm using wordpress as cms.

Updating MySQL db

<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="hsp_property"; // Database name
$tbl_name="project_directory"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//Get values from form
$id = $_POST['id'];
$hospital = $_POST['hospital'];
$project = $_POST['project'];
$state = $_POST['state'];
$status = $_POST['status'];
$da_status = $_POST['da_status'];
$pm = $_POST['pm'];
$budgett = $_POST['budgett'];
$budgetat = $_POST['budgetat'];
$pdapproval = $_POST['pdapproval'];
$pdcs = $_POST['pdcs'];
$pdcd = $_POST['pdcd'];
$pdcf = $_POST['pdcf'];
$pnm = $_POST['pnm'];
$prm = $_POST['prm'];
$comments = $_POST['comments'];
// update data in mysql database
$sql="UPDATE $tbl_name SET Hospital='$hospital', Project='$project', State='$state',Project_Status='$status',DA_Status='$da_status',Project_Manager='$pm',Budget_Total='$budgett',Budget_Approved='$budgetat',Project_Approval_Dates='$pdapproval',Project_Contstruction_Dates='$pdcs',Project_Contract_Dates='$pdcd',Project_Current_Dates='$pdcf',Program_Next_Milestone='$pnm',Program_Milestone='$prm',Comments='$comments' WHERE id='$id'";
$result=mysql_query($sql);
// if successfully updated.
if ($result) {
header ('Location: ../project_directory.php');
}
else {
echo 'Error';
}
?>
The above is some code to update a MySQL db, i'm running WAMP to test the website before I'll upload.
I've been using the phpeasysteps tutorial as php and mysql is new to me. It's been working all ok until now.
Would love to know what i'm doing wrong, the PhpEasySteps tutorial might be a tad old as i've had to update a few elements of the initial code to get it to work..
Replace echo 'Error'; with echo mysql_error(); to see why you didn't get a result and then slap yourself for misspelling a column name or something most likely easily overlooked. If you still can't figure it out, post the error. And if you go that far, post the result of SHOW CREATE TABLE project_directory
You need to add $link_identifier to your mysql_select_db database selection,
Syntax: bool mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )
$link = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name", $link)or die("cannot select DB");
You can use mysql_error(); function to find the mysql related errors.

Hostgator SQL database not updating with PHP form

I have a PHP form that should insert data into my SQL database on hostgator. However it is not adding any data but the id field keeps incrementing. I do not receive any error message when submitting the form and when i go to the database the other fields are just empty thus not displaying any data.
I am pulling my hair and cant figure out what the problem is. Can someone please help me
Thanks
<?php
$host="localhost"; // Host name
$username="xxxxxx"; // Mysql username
$password="xxxxxx"; // Mysql password
$db_name="rob1124_inventory"; // Database name
$tbl_name="data"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$qty=$_POST['qty'];
$product=$_POST['product'];
$price=$_POST['price'];
$totalprice=$_POST['totalprice'];
$seller=$_POST['seller'];
$city=$_POST['city'];
// Insert data into mysql
$sql="INSERT INTO $tbl_name(qty, product, price, totalprice, seller,city)
VALUES('$qty', '$product', '$price', '$totalprice', '$seller', '$city')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
Change to utf-8 from all varchar fields of your table and
try to get mysql_error().
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
mysql_query("set names 'utf8'");
//You codes....
// Insert data into mysql
$sql="INSERT INTO $tbl_name(qty, product, price, totalprice, seller,city)
VALUES('$qty', '$product', '$price', '$totalprice', '$seller', '$city')";
$result=mysql_query($sql) or die(mysql_error());
//Your codes...
Since the id is incrementing atleast the form and the DB connect, it tries to enter data.
One usually occurring error is that the data types in the databases columns don't match with the type of data recieved. Like trying to insert chars into ints etc. Or the length of the data is to large for the assigned size in the database. Check to see that the types are correct and try again.
But still, those that are correct should be inserted. Hard to tell without knowing more about the database design.

number format in SQL INSERT

Hi guys i need some support on number format in SQL INSERT INTO
i need to convert {$data['rank']['points']} as number format, so that instead of it showing as 5467389 it converts it to 54,673,89
the data is being imported from API Data
this is my code
$host="hostname"; // Host name
$username="database"; // Mysql username
$password="password"; // Mysql password
$db_name="dbname"; // Database name
$tbl_name="table"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// API Data
$url = "http://api.erpk.org/citizen/profile/3121752.json?key=Yn3AsG80";
$json = $json = file_get_contents($url);
$data = json_decode($json, true);
date_default_timezone_set('Europe/London');
// Insert data into mysql
$sql="INSERT INTO $tbl_name(citid, citname, rankpoints)VALUES('{$data['id']}', '{$data['name']}', '{$data['rank']['points']}')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='supplies_insert.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
Try this:
$query = sprintf("INSERT INTO `%s` (citid, citname, rankpoints) VALUES ('%s', '%s', '%s')",
mysql_real_escape_string($tbl_name),
$data['id'],
mysql_real_escape_string($data['name']}),
mysql_real_escape_string(number_format($data['rank']['points'])));
$result = mysql_query($query);
You can use php's number_format() function if I understand your requirement correctly. Let me know if that's not what you want.

Categories