Inserting data trouble with my code - php

Hi i was using this code in the last months but suddenly it stop working and it doesn't store the data in the database, it's config with the auto increment value and it just stopped in the "87" after that i can't make it to work
<?php
$connect = mysql_connect("host","user","pass");//database connection
if($connect){
echo("+");
}else{
echo("-");
}
$make = mysql_select_db("database");
if($make){
echo("+");
}else{
echo("-");
}
// Get values from form
$renovarum=$_POST['repnovarum'];
$cargorepnov=$_POST['cargorepnov'];
$razonsocial=$_POST['razonsocial'];
$rfcli=$_POST['rfcli'];
$representante=$_POST['representante'];
$cargorepcli=$_POST['cargorepcli'];
$nombrecomercial=$_POST['nombrecomercial'];
$calleynum=$_POST['calleynum'];
$calle3=$_POST['calle3'];
$calle5=$_POST['calle5'];
$calle6=$_POST['calle6'];
$calle4=$_POST['calle4'];
$personafm=$_POST['personafm'];
$escritura=$_POST['escritura'];
$fechaescr=$_POST['fechaescr'];
$abogado=$_POST['abogado'];
$numnotario=$_POST['numnotario'];
$ciudades=$_POST['ciudades'];
$numcomer=$_POST['numcomer'];
$fechapro=$_POST['fechapro'];
$emailcont=$_POST['emailcont'];
$liderproyecto=$_POST['liderproyecto'];
$fechainicio=$_POST['fechainicio'];
$fechavencimiento=$_POST['fechavencimiento'];
$entregables=$_POST['entregables'];
$inforeq=$_POST['inforeq'];
$pago=$_POST['pago'];
$pago2=$_POST['pago2'];
$formadepago=$_POST['formadepago'];
$diaspago=$_POST['diaspago'];
$fecprimerpago=$_POST['fecprimerpago'];
$telefono=$_POST['telefono'];
//inserting data order
$order = "INSERT INTO contratos_finales2
(repnovarum,cargorepnov,razonsocial,rfc,representante,cargorepresentante,nombrecomercial,calleynum,colonia, ciudad,estado,cp,tiporeg,numescritura,fechaescritura,nombrenotabo,numnotpub,ciudadescr,numpropycom,fechaproycom, emailcont,liderproy,fechaini,fechafin,entregables,inforeq,cantnum,canletra,formadepago,diadepago,fechaprimerpago,telefono)
VALUES
('$renovarum','$cargorepnov','$razonsocial','$rfcli','$representante','$cargorepcli','$nombrecomercial','$calleynum','$calle3','$calle5','$calle6','$calle4','$personafm','$escritura','$fechaescr','$abogado','$numnotario', '$ciudades','$numcomer','$fechapro','$emailcont','$liderproyecto','$fechainicio','$fechavencimiento','$entregables','$inforeq','$pago','$pago2','$formadepago','$diaspago','$fecprimerpago','$telefono')";
//declare in the order variable
$result = mysql_query($order); //order executes
if($result)
{
echo("
+");
}
else
{
echo("
-");
}
?>
i need to keep saving the data in the form but i can't make it work i don't know if i have to make a change i didn't change anything in the database it's te same version and connection from the beginning.

Please check the data type of your auto increment field, it may possible that your data type is tiny int or have less length. You need to change your datatype to INT and length as 11 or as per your requirement.

Your code is vulnerable to sql injection. Who knows what one did to your database. At least do a minimum sanitization with mysql_real_escape_string();
Can you add data to your table from phpmyadmin via UI? Any error messages? Try to run your query in phpmyadmin's cmd tool.

please correct this
$make = mysql_select_db("database");
$connect = mysql_connect("hostname","username","password");//database connection
$make = mysql_select_db("database",$connect);
bool mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )
please take a look here

Related

PHP Mysql query data not correct

I am a newbie Programmer here, I want to know why my code does not get the correct data from my Mysql DB.
mysql_connect('localhost',"root","password");
mysql_select_db("Torch");
$playerbal = mysql_query("SELECT money FROM table WHERE name = '$player'");
If I use this code, then I get the $playerbal as Resource id #7
I have found some solutions for this Resouce id #7 error. If I use mysql_fetch_array, I get just "Array"
mysql_* functions are now deprecated and shouldn't be used anymore.
Your code isn't working because you need to use mysqli_fetch_array() in order to retrieve the actual data in the table using a DB connection handler
Try using something like this :
//Create DB connection
$con=mysqli_connect("localhost","root","password","Torch");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
$result = mysqli_query($con, "SELECT money FROM table WHERE name = '$player'") or die(mysqli_error($con));
//Retrieve the info(row) from the retrieved recordset and loop through it
while($row = mysqli_fetch_array( $result )) {
//Retrieve the needed field from the row
$data=$row['money'];
//do your stuff here
}
//Close connection
mysqli_close($con);
BTW Don't forget to sanitize your inputs.
mysql_query() statement returns a resource pointer to the result set, not the data itself. You'll need to use mysql_fetch_array() in order to retrieve the actual data in the table.
here's the sol
$row = mysql_fetch_array($playerbal);
$data = $row['money'];
echo $data;
If you want to get all rows of money column then use this code-
mysql_connect('localhost',"root","password");
mysql_select_db("Torch");
$playerbal = mysql_query("SELECT money FROM table WHERE name = '{$player}'");
while($data = mysql_fetch_array($playerbal)){
echo $data[0]; //there is only one column so this column is stored into 0 index.
}

Building interactive WHERE clause for Postgresql queries from PHP

I'm using Postgresql 9.2 and PHP 5.5 on Linux. I have a database with "patient" records in it, and I'm displaying the records on a web page. That works fine, but now I need to add interactive filters so it will display only certain types of records depending on what filters the user engages, something like having 10 checkboxes from which I build an ad-hoc WHERE clause based off of that information and then rerun the query in realtime. I'm a bit unclear how to do that.
How would one approach this using PHP?
All you need to do is recieve all the data of your user's selected filters with $_POST or $_GET and then make a small function with a loop to concatenate everything the way your query needs it.
Something like this... IN THE CASE you have only ONE field in your DB to match with. It's a simple scenario and with more fields you'll need to make it so that you add the field you really need in each case, nothing too complex.
<?php
//recieve all the filters and save them in array
$keys[] = isset($_POST['filter1'])?'$_POST['filter1']':''; //this sends empty if the filter is not set.
$keys[] = isset($_POST['filter2'])?'$_POST['filter2']':'';
$keys[] = isset($_POST['filter3'])?'$_POST['filter3']':'';
//Go through the array and concatenate the string you need. Of course, you might need AND instead of OR, depending on what your needs are.
foreach ($keys as $id => $value) {
if($id > 0){
$filters.=" OR ";
}
$filters.=" your_field = '".$value."' ";
}
//at this point $filters has a string with all your
//Then make the connection and send the query. Notice how the select concatenates the $filters variable
$host = "localhost";
$user = "user";
$pass = "pass";
$db = "database";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "SELECT * FROM table WHERE ".$filters;
$rs = pg_query($con, $query) or die("Cannot execute query: $query\n");
while ($row = pg_fetch_row($rs)) {
echo "$row[0] $row[1] $row[2]\n";
//or whatever way you want to print it...
}
pg_close($con);
?>
The above code will get variables from a form that sent 3 variables (assuming all of them correspond to the SAME field in your DB, and makes a string to use as your WHERE clause.
If you have more than one field of your db to filter through, all you need to do is be careful on how you match the user input with your fields.
NOTE: I did not add it here for practical reasons... but please, please sanitize user input.. ALWAYS sanitize user input before using user controlled data in your queries.
Good luck.
Don't do string concatenation. Once you have the values just pass them to the constant query string:
$query = "
select a, b
from patient
where
($x is not null and x = $x)
or
('$y' != '' and y = '$y')
";
If the value was not informed by the user pass it as null or empty. In the above query the x = $x condition will be ignored if $x is null and the y = '$y' condition will be ignored if $y is empty.
With that said, a check box will always be either true or false. What is the exact problem you are facing?
Always sanitize the user input or use a driver to do it for you!
I have created a Where clause builder exactly for that purpose. It comes with the Pomm project but you can use it stand alone.
<?php
$where = Pomm\Query\Where::create("birthdate > ?", array($date->format('Y-m-d')))
->andWhere('gender = ?', array('M'));
$where2 = Pomm\Query\Where::createWhereIn('something_id', array(1, 15, 43, 104))
->orWhere($where);
$sql = sprintf("SELECT * FROM my_table WHERE %s", $where2);
$statement = $pdo->prepare($sql);
$statement->bind($where2->getValues());
$results = $statement->execute();
This way, your values are escaped and you can build dynamically your where clause. You will find more information in Pomm's documentation.

SQL Table not updating in PHP

I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows

PHP not returning results from MySQL query as expected

I'm trying to create a variable which is dependent on some information from the database. I'm trying to generate a $path variable which stores a path, depending on what information is recovered from the database.
$linkid = mysql_connect('localhost','user','password');
mysql_select_db("table", $linkid);
$variable = "00001";
$groupID = null;
$temp = mysql_query("SELECT groupID FROM table WHERE memberID='$variable'", $linkid);
while ($row = mysql_fetch_row($temp)){
global $groupID;
foreach ($row as $field){
$groupID = $field;
}
}
....
$path = "C:\WAMP\www\project\\" . $groupID;
$dir_handle = #opendir($path) or die('Unable to open $path');
The idea behind this is that $variable is set before the PHP is run, however it's set to 00001 for testing. The ideal situation is that $path should equal C:\WAMP\www\project\00001\. Currently, when I echo back the $path all I get is the original path without the $groupID added to the end.
I also receive the message "mysql_fetch_row() expects parameter 1 to be resource" but I've used this method for retrieving information before and it worked just fine, and I set up my table in the same way so I don't think the issue is there.
I have a feeling I'm missing something obvious, so any help is appreciated. It's not for an assignment or anything school related (just trying stuff out to learn more) so knock yourselves out with correcting it and explaining why :)
In addition, only one memberID will ever be a match to the $variable, so if there's an alternative way to fetch it I'd appreciate knowing.
Oh, and I know my variable names are shocking but they're only that on here, on my actual code they're different so no criticism please :p
EDIT: The SQL query is correct, after following BT634's advice and when running it on phpMyAdmin I get the groupID I want and expect.
mysql_select_db("table", $linkid)
should actually be
mysql_select_db("database_name", $linkid)
since you are connecting to the database that contains the table and not the table itself.
Also, try mysql_result($temp,0) instead of the while loop
First of all, you're not specifying what database to connect to in your connection - you're specifying what table. You might also want to check how many rows your query is returning:
$temp = mysql_query("SELECT groupID FROM table WHERE memberID='$variable'", $linkid);
echo mysql_num_rows($temp);
If it's still complaining about $temp not being a valid resource, change your MySQL connection code to:
// Establish connection
$con = mysql_connect("localhost","peter","abc123");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("my_db", $con);
// Make your query
$result = mysql_query("SELECT groupID FROM table WHERE memberID='$variable'");
// Find out what the value of the query is (i.e. what object/resource it is)
var_dump($result);
Once you know that MySQL is returning valid data, extract the values you want. You don't have to use globals:
while ($row = mysql_fetch_row($temp)){
$groupId = $row[0];
}
// Use $groupId however you please...
One thing to bear in mind is that mysql_fetch_row will return
array
(
0 => '...'
)
Whilst mysql_fetch_assoc will return:
array
(
'groupId' => '...'
)
Find out what query it's definitely running, and paste that into a normal MySQL client to make sure your query is correct.
Just do this after defining "$variable"
exit("SELECT groupID FROM table WHERE memberID='$variable'");
Then copy the output into a MySQL client (or MySQL from the command line).
Try something like this:
global $groupID;
$linkid = mysql_connect('localhost','user','password');
mysql_select_db("table", $linkid);
$variable = "00001";
$groupID = null;
$sql = "SELECT groupID FROM table WHERE memberID='$variable'";
$temp = mysql_query($sql, $linkid) or die(mysql_error());
$row = mysql_fetch_row($temp);
if ($row) {
$groupID = $row['groupID'];
}
If you are retrieving a single value, and it is guaranteed to be unique, then the loop structures are unnecessary. I've added a check to ensure the query exits with an error if there's a problem - it is ideal to do this everywhere, so for example do it with mysql_select_db too.

PHP and SQL getting latest entry in DB from DateTime

I have a database which id,title,subject and datetime and I'm calling a php page that takes in a request from clients to show the latest entry in the db from the difference of time from the client and checks with the last entry's datetime. PHP code as follows
$date = "2012-10-06 18:13:52";
//Establish a connection
$conn = mysql_connect('localhost','regadmin','regadmin');
//Select the mySQL db
$db = mysql_select_db('easy_comm', $conn);
$sql = mysql_query("SELECT `title`, `subject`,`date_sent` FROM `books` WHERE `date_sent` > '$date'", $conn);
$count=mysql_num_rows($sql);
if($count != 0){
$json = array('boolean' => true);
}
else{
$json = array('boolean' => false);
//echo "No record";
}
From the above code and the provided $date variable, it will always return true and the last entry is
2012-10-06 18:10:52
I have tried converting to UNIXTIMESTAMP but same problem
Well this works good enough for me.Please make sure the column against which you are comparing the date surely happens to be DATETIME column not a VARCHAR or something else.
Please post us database structure to see the collation as well and also try printing the query on the fly and then execute in your console.

Categories