php add to database with insert statment - php

I have a simple insert statement that should use $GLOBALS that has my connection string in. Problem is that it does not insert the data. Have I done this correctly?
Insert.php
<?php
require 'core/init.php';
$Name = $_REQUEST["Name"];
$Venue = $_REQUEST["Venue"];
$Category = $_REQUEST["Category"];
$query = "INSERT INTO bands (Name, Venue, Category)
VALUES ('$Name', '$Venue', '$Category')";
mysql_query ($query,$GLOBALS)
or die ("could not add to database");
echo("You have added: <br />");
$result = mysql_query("SELECT * FROM bands ORDER BY Band_id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
echo $row['Name']. "" . $row['Venue']. "" . $row['Category'];
echo "<br />";
}
?>

You need to connect mysql with mysql_connect() function then select database with mysql_select_db() function then you can call mysql_query function
you just cant execute queries with query string parameter you need to execute that connection query first and then select your database
And i suggest you to use mysqli instead of mysql cuz mysql methods will be deprecated soon

You don't put whole $GLOBALS variable in your mysql_query() call. You put the specific variable with the connection string only:
mysql_query($query, $GLOBALS['connection']) // Assuming you called the connection var "connection"
or die ("could not add to database");

Related

Get a row from a database based on querystring

BIt of a php/mysql noob here, hope someone can help.
Ok so i have a URL which has an id in the querystring like so: wwww.mysite.com/page1.php?id=1
What i want to do is connect to a table in the database and get the data from the columns on one row where the first column named ID equals the id number held in the querystring.
I then want to print the data from each column in different div's elsewhere on the page.
There's also the additional issue of what to do if there's no row in the table with the same id as the querystring, i'd want it to change the id in the querystring to 1 and load that rows data.
I had a little go, i know it connects ok but i have no idea if the rest is what i want:
<?php
$link = mysql_connect('Address', 'Database', 'Password');
if (!$link) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = "select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per=".$_GET['ID']."";
echo $result['A'];
mysql_close($link);
?>
And then put this in the div's to print the data.
<?php echo $result['A']; ?>
Am i along the right lines or completely wrong?
$dbConnection = mysql_connect('Address', 'Database', 'Password');
if (!$dbConnection) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = $dbConnection->prepare("select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per = ?");
$query->bind_param('s', $per);
$query->execute();
$result = $query->get_result();
<?php echo $result; ?>
use this code first to avoid SQL Injection second that's the way it should work in PHP first prepare the query second execute and only then show it.
Use mysql_query function in your code.
mysql_* functions is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used.
<?php
$link = mysql_connect('Address', 'Database', 'Password');
if (!$link) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = "select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per=$per";
$result = mysql_query($query, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['A'];
mysql_close($link);
?>

Query is not running when i try to run it using mysql_query() command

I am trying to test if this query runs or not.But i am output with blank screen i.e no output. I am using xampp server.
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_pass='';
$mysql_db='a_database';
$con_error='connection error';
$query="SELECT `name` FROM `users` WHERE `id`='1' "; //selecting name from databas where id is 1
$query_run=mysql_query($query); //this is my query
if($query_run)
{
echo 'success';
}
?>
Please help me with this. $query_run neither returns false here nor true. I am not able to understand where the problem is.
First of all try to avoid mysql_* functions from php > 5.4, use mysqli_* function like this.
connect to Databse before running a query like this
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$query="SELECT `name` FROM `users` WHERE `id`='1' "; //selecting name from databas where id is 1
$query_run=mysqli_query($con,$query);
For php < 5.5 use this
$con=mysql_connect("localhost","my_user","my_password","my_db");
$query="SELECT `name` FROM `users` WHERE `id`='1' "; //selecting name from databas where id is 1
$query_run=mysql_query($con,$query);
First of all stop using mysql it is deprecated. Use mysqli now.
In your script you missed the connection to database. Add before your query:
$link = mysqli_connect($mysql_host,mysql_user,$mysql_pass,$mysql_db) or die("Error " . mysqli_error($link));
For more details see this link.
try this:::
<?php
$link = mysqli_connect("localhost","root","root","a_database") or die("Error " . mysqli_error($link));
$query = "SELECT name FROM users" or die("Error in the consult.." . mysqli_error($link));
$result = $link->query($query);
while($row = mysqli_fecth_array($result)) {
echo $row["name"] . "<br>";
}
?>
as mentioned there, use mysqli_*

mysql_insert_id() not returning a value -

I need to retrieve the auto increment field from my database table. I tried the following but $id is always just empty.
The insert works too.
My table is as follows:
idint(9) NOT NULL auto_increment,
and id is set as primary
What am I doing wrong?
$conn = mysql_connect($host,$username,$password);
mysql_select_db($database, $conn) or die( "Unable to select database");
include "update_activity.php";
updateActivity("logged in", "On Break");
$date = date("m/d/y"); $starttime = time();
$sesh = $_SESSION['fname']." ".$_SESSION['lname'];
$q = "INSERT INTO `breaks` (date, starttime, user) VALUES ('".$date."', '".$starttime."', '".$sesh."')";
$query = mysql_query($q, $conn);
$id = mysql_insert_id($conn);
echo var_dump($id); exit;
edited to show my more recent attempts
Have read all comments given and your replies to each.
Only one of these is possible:
Either the query works properly OR
You are not getting the generated primary key.
Both of these can never be true.
Define, how you know query is working? Do you know the max PK before and after the running query? Is the insert happening from some other place or thread or even other user? the query is working properly from code or from your mysql client?
To diagnose the problem, we have to go though the normal way.
Dump your generated query before calling mysql_query.
Wrap a error checking system around your query call so php can tell you if the query worked or not. I am sure just by these two steps you will realize the root cause of the problem.
error_reporting(E_ALL);
ini_set('display_errors','on');
echo "before calling: $q\n";
$query = mysql_query($q, $conn);
if(!$query)
{
echo "Error:" . mysql_error($conn);
return;
}
echo " generated id:" . mysql_insert_id($conn);
#adelphia as far as i get the idea there is a problem in the query that is executed.
plz check the query properly
Borrow a lead from this code extracted from here:
http://php.net/manual/en/function.mysql-insert-id.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
The problem with your insert query
$q = "INSERT INTO `breaks` (date, starttime, user)
VALUES ('".$date."',
'".$starttime."',
'".$_SESSION['fname'] $_SESSION['lname']."')";
try with this
and main thing you are using most of the deprecated "mysql" things like "mysql_insert_id()"
store the values that u want to pass into an array or variable and pass it in the insert query.
its should work fine then...

How to convert a string to variable through a loop and save it in MySQL Database

I have this problem. This is my PHP code to take one MySQL table and Insert the data into another MySQL table:
<?php
$connect = mysql_connect("host","user","password");
if (!$connect){
die("Failed to connect to the database: ".mysql_error());
}
$kies_bd = mysql_select_db("eraenz_db1",$connect);
if (!$kies_bd){
die("failed to choose from BD: ".mysql_error());
}
$query = "SELECT ListNumber FROM residential";
$result1 = mysql_query($query);
if (mysql_num_rows($result1) >10){
$difference = mysql_num_rows($result1) - 10;
$myQuery = "SELECT * FROM residential ORDER BY id LIMIT 10, $difference";
$result2 = mysql_query($myQuery);
while ($line = mysql_fetch_array($result2)){
mysql_query("INSERT INTO lisitngs
(listnumber, mandatetype, listdate,expirydate, updatedate,virtualtoururl,status,propertyright,agnt_id, erfsize,erf_no, housesize,outbuildingsize, bathroomoptions,closedusergroup,facingoptions,features,kitchenoptions,flatlet,parking,carport,price,numofbath,numofbed, numofgarages, numofkitchens, numofreception,numofstudies,numofdomesticbath,numofdomesticbed,numofoutsidetoil,off_id,ownershiptype, parkingdesc, pooloptions,pool,sellingreason,sfeatureoptions,roofoptions,roomoptions,walloptions,windowoptions, styleoptions,securityoptions,tempcontrol,streetname,streetnumber, suburb, propertycategory,propertytype,ss_name,agentcontactname,province,city, postalcode,email,listingstatus,feedtype, rates, levies)
values ({$line['ListNumber']}','{$line['MandateType']}','{$line['ListDate']}','{$line['ExpiryDate']}','{$line['UpdateDate']}','{$line['VisualTourURL']}','{$line['Status']}','{$line['PropertyCategory']}','{$line['AgentI']}','{$line['SizeOfErf']}','{$line['StandNumber']}','{$line['SizeOfHouse']}','{$line['SizeOfOutBuildings']}','{$line['BathroomOptions']}','{$line['ClosedUserGroup']}','{$line['FacingDescrip']}','{$line['Features']}','{$line['KitchenOptions']}','{$line['Flatlet']}','{$line['Parking']}','{$line['NumOfCarports']}','{$line['ListPrice']}','{$line['NumOfBathrooms']}','{$line['NumOfBedrooms']}','{$line['NumOfGarages']}','{$line['NumOfKitchens']}','{$line['NumReceptionRooms']}','{$line['NumStudies']}','{$line['NumOfDomBathrooms']}','{$line['NumOfDomBedrooms']}','{$line['NumOfOutSideToilets']}','{$line['OfficeId']}','{$line['OwnershipType']}','{$line['ParkingDesc']}','{$line['PoolOptions']}','{$line['Pool']}','{$line['ReasonForSelling']}','{$line['SpecialFeatures']}','{$line['RoofOptions']}','{$line['RoomOptions']}','{$line['WallFinishes']}','{$line['Windows']}','{$line['StyleOptions']}','{$line['SecurityOptions']}','{$line['TempControl']}','{$line['StreetName']}','{$line['StreetNumber']}','{$line['Suburb']}','{$line['PropertyCategory']}','{$line['TypeOfProperty']}','{$line['UnitName']}','{$line['AgentContactName']}','{$line['Province']}','{$line['City']}','{$line['PostalCode']}','{$line['SellerEmail']}','{$line['Status']}','{$line['FeedType']}','{$line['MunRatesTaxes']}','{$line['MonthlyLevy']}')");
mysql_query("INSERT INTO clients
(clnt_title,clnt_name,clnt_surname,clnt_street_name,clnt_street_no,clnt_complex_name,clnt_unit_no,clnt_suburb,clnt_city,clnt_cell,clnt_email,agnt_id,)
values ({$line['SellerTitle']}','{$line['SellerFirstName']}','{$line['SellerSurname']}','{$line['StreetName']}','{$line['StreetNumber']}','{$line['UnitName']}','{$line['UnitNumber']}','{$line['Suburb']}','{$line['City']}','{$line['SellerMobileNumber']}','{$line['SellerEmail']}','{$line['AgentID']}')");
mysql_query("DELETE FROM residential WHERE ListNumber={$line['ListNumber']}");
echo "{$line['ListNumber']} was deleted <br/>";
}
}
mysql_close($connect);
?>
Now not all of these columns are compatible with their counter part column where it is supposed to be inserted into.
My question to you is, how do I save these incompatible strings into a variable and then insert them into the Database Table?
Use Prepared Statements. PHP will convert the type automatically for you, and you're protected against Injection Attacks.
Actually, you should be using Prepared Statements everywhere in your code... building SQL from strings is a bad habit.

MySQL parameter resource error

Here is my error:
Warning: mysql_query() expects parameter 2 to be resource, null given...
This refers to line 23 of my code which is:
$result = mysql_query($sql, $connection)
My entire query code looks like this:
$query = "SELECT * from users WHERE userid='".intval( $_SESSION['SESS_USERID'] )."'";
$result = mysql_query($query, $connection)
or die ("Couldn't perform query $query <br />".mysql_error());
$row = mysql_fetch_array($result);
I don't have a clue what has happpened here. All I wanted to do was to have the value of the users 'fullname' displayed in the header section of my web page. So I am outputting this code immediately after to try and achieve this:
echo 'Hello '; echo $row['fullname'];
Before this change, I had it working perfectly, where the session variable of fullname was echoed $_SESSION['SESS_NAME']. However, because my user can update their information (including their name), I wanted the name displayed in the header to be updated accordingly, and not displaying the session value.
Your $connection variable is NULL that's what your error message is referring to.
Reason being is that you have not called mysql_connect. Once called it will assign you a resource where you can set it to the $connection variable, thus being non-null.
As an example:
$connection = mysql_connect('localhost', 'mysql_user', 'mysql_password');
// now $connection has a resource that you can pass to mysql_query
$query = "SELECT * from users WHERE userid='".
intval( $_SESSION['SESS_USERID'] )."'";
$result = mysql_query($query, $connection)
include the mysql connections on your class file, for example:
connections/mysql.php
<?
$hostname_MySQL = "localhost";
$database_MySQL = "database";
$username_MySQL = "user";
$password_MySQL = "password";
$MySQL = mysql_pconnect($hostname_MySQL, $username_MySQL, $password_MySQL) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_MySQL,$MySQL);
?>
class.php
<?
include "Connections/MySQL.php";
class utils {
public function myFunction()
{
global $MySQL;
$sql = "select * from table";
$rs = mysql_query($sql, $MySQL) or die(mysql_error());
$filas = mysql_fetch_assoc($rs);
$totalFilas = mysql_num_rows($rs);
...
}
}
?>
You have two ways of doing this, you need to use mysql_connect to connect to your database, you can pass this to mysql_query if you desire, if you don't pass anything to mysql_query PHP uses the last link opened from mysql_connect
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
Have you connected to your database? If so please show this code too.
For now, just try removing the $connection variable, like this:
$result = mysql_query($query);
And see where that gets you.
$connection is assigned the value of the database connection resource id. You don't have that in your script, so the value of $connection is NULL, and that is why you are getting the error. You need to connect to the database before using mysql_query(). You should be okay after that.
You need to do:
$connection=mysql_connect('host','user','pass');
if($connection === false) {
echo "Error in connection mysql_error()";
}

Categories