hello i have a problem insert data to mysql working but i need if not exist data create if exist update all row.
Now after each refresh page add same data but not updating.
$conn = mysql_connect("127.0.0.1", "root","") or die(mysql_error());
mysql_select_db("youtuberiai", $conn);
echo "Connected successfully <br /><br />";
$url = 'https://www.googleapis.com/youtube/v3/channels?id=ID&part=snippet%2Cstatistics&key=KEY';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json as $row);
foreach($json['items'] as $row)
{
$idd = $row['id'];
$title = $row['snippet']['title'];
$description = $row['snippet']['description'];
$viewCount = $row['statistics']['viewCount'];
$subscriberCount = $row['statistics']['subscriberCount'];
$sql = "INSERT INTO vartotojai(idd, title, description, viewCount, subscriberCount) VALUES('$idd', '$title','$description','$viewCount','$subscriberCount')
ON DUPLICATE KEY UPDATE idd='$idd', title='$title', description='$description', viewCount='$viewCount', subscriberCount='$subscriberCount';
";
mysql_query("SET NAMES utf8");
if(!mysql_query($sql,$conn))
{
die('Error : ' . mysql_error());
}
}
make the id as unique. Then only duplicate query gets the role. If the value in that filed already exist, then then that field will be updated.
Related
I'm trying to make a Check-in/out system.
So far I have a dropdown that get the list of active events.
<select name="events">
<?php
$conn = new mysqli('localhost:3306', 'user', 'pw', 'database') or die ('Cannot connect to db');
$eveny = $conn->query("select event_title from events_event where inactive=0");
while ($row=mysqli_fetch_array($eveny)) {
unset($event);
$event = $row['event_title'];
echo '<option value="'.$event.'">'.$event.'</option>';
}
?>
</select>
And a textbox that searches users based on first name, but it auto displays results (like a Google search) and then fills out the info with both First Name and Last name. Source.
The only change in the php is the echo to show both first and last names as follows:
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<p>" . $row["per_FirstName"] . " " . $row["per_LastName"] . "</p>";
}
NOW FOR THE PROBLEM
I have made the frontend into a form, and a submit button using method="post".
But something in my php is not functioning/lacking.
<?php
$db = new mysqli('localhost:3306', 'user', 'pw', 'database') or die ('Cannot connect to db');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$myname = mysqli_real_escape_string($db,$_POST['fullname']);
$eventy = mysqli_real_escape_string($db,$_POST['events']);
//$checktime = mysqli_real_escape_string($db,date("Y-m-d H:i:s"));
$evid = "SELECT event_id from events_event where event_title = '$eventy'";
$revvy = mysqli_query($db,$evid);
$nameParts = explode(' ', $myname);
$firstName = trim($nameParts[0]);
$lastName = trim($nameParts[1]);
$sql = "SELECT per_ID FROM person_per WHERE per_FirstName = '$firstName' AND per_LastName = '$lastName'";
$result = mysqli_query($db,$sql);
//$row = mysqli_fetch_row($result);
//$result = $result->fetch_all();
while($row = mysqli_fetch_assoc($result)){
$perID = $row['per_ID'];
}
while($row2 = mysqli_fetch_assoc($revvy)){
$evvy = $row['event_ID'];
}
$count = mysqli_num_rows($result);
// table row must be 1 row if it succeeded
if($count == 1) {
//session_register("myname");
//$_SESSION['login_user'] = $myname;
$checkin = "insert into event_attend (attend_id, event_id, person_id, checkin_date) values (DEFAULT, '$evvy', '$perID', now())" or die(mysqli_error());;
mysqli_query($db,$checkin);
header("location: checkedin.php");
}else {
$error = "An error occurred.";
}
}
?>
The $myname, is the result of both first name and last name, I need just First Name based on the filled out text field which uses both first and last names.
I also can't get the Event_ID from the dropdown.
If user's first and last name are separated by space:
$nameParts = explode(' ', $myname);
$firstName = trim($nameParts[0]);
I've created a table and stored values in it. The table has a column 'ID' which is unique.
Now I’ve created a form where there is a button marked Retrieve. When I enter the ID and click the Retrieve button, I want to view the data corresponding to this ID.
How do I do this using PHP and MYSQL?
I’ve got some code below, but it isn‘t working. No error message is being showed. But there is no problem with the db connection. Rest of the functions working except for 'RETRIEVE'.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error())
{
die("couldn't connect" . $conn->connect_error());
}
echo ("connected successfully");
$id = $_POST['Id'];
$name = $_POST['Name'];
$blood = $_POST['BloodGroup'];
if(isset($_POST['insert'])){
$insert = "Insert into ins(Id, name, BloodGroup) values ('$id','$name', '$blood')" ;
if($conn->query($insert) === TRUE) {
echo ("Input data entered successfully");
} else {
echo ("Input data failed to be entered" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['update'])) {
$update = "update ins set Name='".$name."', BloodGroup='".$blood."' where Id='".$id."'";
mysql_query($update);
if($conn->query($update) === TRUE) {
echo ("Data updated successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['delete'])) {
$id = $_POST['Id'];
$delete = "delete from ins where Id='".$id."'";
if($conn->query($delete) === TRUE) {
echo ("Data deleted successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
}
else {
$id = $_POST['Id'];
$retrieve = "SELECT * FROM ins WHERE Id = ".'$id'."";
$dis = $db->query($retrieve);
$row = $dis->fetch_assoc();
echo 'Details are: '.$row['id'];
}
}
$conn->close();
?>
Change sql select clause into this:
"SELECT * FROM ins WHERE Id = " .$id. " LIMIT 1";
$retrieve = "SELECT * FROM ins WHERE Id = ".$id." LIMIT 1";
The limit will work for you
In the SQL statement ($retrieve), the single quotes are killing it for you. Try either of the following:
Remove the single quotes around $id and keep the rest of the statement the same
Change '$id' to "'{$id}'" (if you're keen on getting the single quotes around the $id value - just in case $id is a text value and not a number)
Try this
$retrieve = "SELECT * FROM ins WHERE Id = ".$id;
$dis = $db->query($retrieve);
$row = $dis->fetch_row();
I'm trying to update product information into the mysql database from edit page, but I'm showing it does not doing anything and even is not showing any errors.
What did I miss?
<?php
$dbcs = new mysqli("localhost", "root", "password", "shopping");
// Check connection
if (mysqli_connect_errno($dbcs))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Parse the form data and update company information to the system
if (isset($_POST['product_name'])) {
$pid = $_POST['thisID'];
$product_name = $_POST['product_name'];
$product_category = $_POST['product_category'];
$product_product_retail_price = $_POST['product_retail_price'];
$product_price = $_POST['product_price'];
// See if that company name is an identical match to another company in the system
$sql = "UPDATE product SET
product_name='$product_name',
product_category='$product_category',
product_retail_price='$product_retail_price',
product_price='$product_price'
WHERE product_id='$pid'" or die(mysql_error());
header("location: product.php");
exit();
}
// Gather these companies full information for inserting automatically into the edit form below on page
if (isset($_GET['pid'])) {
$targetID = $_GET['pid'];
$sql = "SELECT * FROM product WHERE product_id='$targetID' LIMIT 1";
$result=mysqli_query($dbcs,$sql);
while($row = mysqli_fetch_array($result)){
$product_id = $row["product_id"];
$product_name = $row["product_name"];
$product_category = $row["product_category"];
$product_retail_price = $row["product_retail_price"];
$product_price = $row["product_price"];
$screenshot =$row["screenshot"];
}
}
mysqli_close($dbcs);
?>
$sql = "UPDATE product SET
product_name='$product_name',
product_category='$product_category',
product_retail_price='$product_retail_price',
product_price='$product_price'
WHERE product_id='$pid'";
$query= mysqli_query($dbcs,$sql);
if(!$query)
{
print "error";
}
else
{
header("your page link");
}
p.s Thankx for correction Hanky Panky:)
This is wrong:
$sql = "UPDATE product SET
product_name='$product_name',
product_category='$product_category',
product_retail_price='$product_retail_price',
product_price='$product_price'
WHERE product_id='$pid'" or die(mysql_error());
You are not executing that query. Execute it with mysqli_query()
$sql = "UPDATE product SET
product_name='$product_name',
product_category='$product_category',
product_retail_price='$product_retail_price',
product_price='$product_price'
WHERE product_id='$pid'";
$result = mysqli_query($dbcs,$sql);
Ummm... Maybe run $result = mysqli_query($dbcs,$sql); after defining the insert $sql?
Also, use the die() after the mysqli_query() not in the $sql string definition.
Additionally, run all those vars through mysqli_real_escape_string() before using them in the query.
I want to load an xml file into a table column with MySQL. How do I do this with an INSERT statement instead of an UPDATE statement?
This code does an INSERT to create a new row, gets the id for the last inserted row, then attempts to do the update to load the xml file. But it doesn't update the row with the xml info.
I would like to know what to fix to put the xml in the database column. I also want to streamline the code and do the LOAD_FILE in one INSERT statement.
MySQL database table structure
Field Datatype Attributes Extra
userid INT(6) unsigned auto_increment
user_events LONGTEXT
PHP code to add xml file
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("hostname","adminuser","adminpassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_db", $con);
$qinsert = "INSERT INTO load_xml (`user_events`) VALUES ('user events')";
$result_insert = mysql_query($qinsert);
$qtext = "SELECT * FROM load_xml";
$result = mysql_query($qtext);
$numrows = mysql_num_rows ( $result );
while ($row = mysql_fetch_row($result)) {
echo 'user id '.$row[0].' user_events '.$row[1].'<br/>';
}
$insert_id = "SELECT LAST_INSERT_ID()";
$rin_id = mysql_query($insert_id);
$row = mysql_fetch_row($rin_id);
$userid = $row[0];
echo 'last added id '.$userid.'<br/>';
$update_xml = "UPDATE load_xml SET user_events=LOAD_FILE('my_events.xml') WHERE userid='$userid'";
$result_update = mysql_query($update_xml);
$qtext = "SELECT * FROM load_xml";
$result = mysql_query($qtext);
$numrows = mysql_num_rows ( $result );
echo $numrows.'<br/>';
while ($row = mysql_fetch_row($result)) {
echo 'user_id '.$row[0].' user_events '.$row[1].'<br/>';
}
mysql_close($con);
?>
Just add the file in the original insert. The file path is that of a file on the server. The mysql user used to connect must have the file privilege. It must be the full path. On windows you need to replace back slashes with forward slashes -
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("hostname","adminuser","adminpassword");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_db", $con);
$qinsert = "INSERT INTO load_xml (`user_events`) VALUES (LOAD_FILE('/full/path/to/my_events.xml'))";
$result_insert = mysql_query($qinsert);
$userid = mysql_insert_id();
echo 'last added id '.$userid.'<br/>';
$qtext = "SELECT * FROM load_xml";
$result = mysql_query($qtext);
$numrows = mysql_num_rows ( $result );
while ($row = mysql_fetch_row($result)) {
echo 'user id '.$row[0].' user_events '.$row[1].'<br/>';
}
mysql_close($con);
?>
UPDATE - here is another version using PDO prepared statement and file_get_contents() -
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db = new PDO('mysql:dbname=test_db;host=hostname', 'adminuser', 'adminpassword');
$qinsert = "INSERT INTO load_xml (`user_events`) VALUES (?)";
$stmt = $db->prepare($qinsert);
$stmt->execute(array(file_get_contents('my_events.xml')));
?>
I must be missing something simple but I don't see it. The following code works great.
<?php
$res = mysql_connect("localhost", "newuser", "");
mysql_select_db("supplydb");
function filter($data)
{
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);
return $data;
}
error_reporting(0);
require("../codebase/grid_connector.php");
$mask5 = filter($_GET["var1"]);
//Get Category ID
$cat = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id='$mask5'");
$rows = mysql_fetch_array($cat, MYSQL_ASSOC);
$array = filter($rows['category']);
//Get Manufactuer ID
$man = mysql_query("SELECT manufacturer_id FROM submissions WHERE submissions.submission_id='$mask5'");
$arows = mysql_fetch_array($man, MYSQL_ASSOC);
$array1 = filter($arows['manufacturer_id']);
function formatting($row)
{
$data = $row->get_value("fda_approved");
if ($data == 1)
$row->set_value("fda_approved", Yes);
else
$row->set_value("fda_approved", No);
}
$gridConn = new GridConnector($res, "MySQL");
function myUpdate($action)
{
$data6 = $action->get_id();
$cat_id = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id ='{$data6}'") or die("Error in query: $query. " . mysql_error());
$rows56 = mysql_fetch_array($cat_id, MYSQL_ASSOC);
$array = filter($rows56['category']);
$status = $action->get_value("approval_status");
$gridConn = new GridConnector($res, "MySQL");
mysql_query("UPDATE submissions SET approval_status='{$status}' WHERE submissions.submission_id='{$data6}'") or die("Error in query: $query. " . mysql_error());
$action->success;
}
$gridConn->event->attach("beforeUpdate", "myUpdate");
$gridConn->event->attach("beforeRender", "formatting");
$gridConn->render_sql("SELECT * FROM submissions JOIN products ON products.product_id = submissions.product_id and submissions.category='$array' and submissions.manufacturer_id='$array1' and submissions.approval_status='0'", "submission_id", "item_number,description,list_price,sugg_price,quantity_per_unit,fda_approved,gpo_contract_number, approval_status");
?>
This code does not
<?php
require("../site_globals/dbc_simple.php");
//$res = mysql_connect("localhost", "newuser", "");
//mysql_select_db("supplydb");
error_reporting(0);
require("../codebase/grid_connector.php");
$mask5 = filter($_GET["var1"]);
//Get Category ID
$cat = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id='$mask5'");
$rows = mysql_fetch_array($cat, MYSQL_ASSOC);
$array = filter($rows['category']);
//Get Manufactuer ID
$man = mysql_query("SELECT manufacturer_id FROM submissions WHERE submissions.submission_id='$mask5'");
$arows = mysql_fetch_array($man, MYSQL_ASSOC);
$array1 = filter($arows['manufacturer_id']);
function formatting($row)
{
$data = $row->get_value("fda_approved");
if ($data == 1)
$row->set_value("fda_approved", Yes);
else
$row->set_value("fda_approved", No);
}
$gridConn = new GridConnector($res, "MySQL");
function myUpdate($action)
{
$data6 = $action->get_id();
$cat_id = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id ='{$data6}'") or die("Error in query: $query. " . mysql_error());
$rows56 = mysql_fetch_array($cat_id, MYSQL_ASSOC);
$array = filter($rows56['category']);
$status = $action->get_value("approval_status");
$gridConn = new GridConnector($res, "MySQL");
mysql_query("UPDATE submissions SET approval_status='{$status}' WHERE submissions.submission_id='{$data6}'") or die("Error in query: $query. " . mysql_error());
$action->success;
}
$gridConn->event->attach("beforeUpdate", "myUpdate");
$gridConn->event->attach("beforeRender", "formatting");
$gridConn->render_sql("SELECT * FROM submissions JOIN products ON products.product_id = submissions.product_id and submissions.category='$array' and submissions.manufacturer_id='$array1' and submissions.approval_status='0'", "submission_id", "item_number,description,list_price,sugg_price,quantity_per_unit,fda_approved,gpo_contract_number, approval_status");
?>
The only difference is the include file at the top and all the include file is is:
<?php
$res = mysql_connect("localhost", "newuser", "");
mysql_select_db("supplydb");
?>
Im fairly new to php but this seems simple and I'm not sure what is getting lost in translation. This works fine on other pages by the way so it must have something to do with the $gridConn = new GridConnector($res, "MySQL"); but I dont know enough to see what. I'm using the DHTMLX javascript library. Could it have something to do with that? Ive tried everything here. Ideas?
Im getting: XML Parsing Error: XML or text declaration not at start of entity Location
Problem is not in the database connection itself, it works correctly and generates data, but result xml corrupted, because some output was started before connector's code.
Check ../site_globals/dbc_simple.php - probably it have some whitespaces|newlines after closing "?>" tag - delete them and it will fix the problem.
Such whitespaces|newlines will not cause harm for HTML pages, but for XML data any extra char at start of document can cause a problem.