Can't Update MySQL table - php

I don't know what I'm doing wrong, but my little update code is giving me an error message that I can't work out how to resolve it.
Here's my code:
<?php
include('dbconfig.php');
$con = mysql_connect($host, $username, $password) or die(mysql_error()) ;
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db, $con);
function sqlEscape($string){
return "'".mysql_real_escape_string($string)."'";
}
if(isset($_POST['submit'])){
$q = "UPDATE records SET `name` = " + sqlEscape($_POST['name']) + ",
`age` = " + sqlEscape($_POST['age']) + ",
`location` = " + sqlEscape($_POST['location']) + ",
`telephone` = " + sqlEscape($_POST['telephone']) + "
WHERE id = $_POST[id]";
mysql_query($q) or die(mysql_error());
}
?>
Here's the error message it prints out:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0' at line 1
Can someone see where I'm going wrong at all?
Thanks for your help.

You are adding strings together with the + operator, which is for adding numbers. In PHP, strings are concatenated with the . (period) operator.
$q = "UPDATE records SET `name` = " . sqlEscape(...) . ",
etc

$q = "UPDATE records SET `name` = " . sqlEscape($_POST['name']) . ",
`age` = " . sqlEscape($_POST['age']) . ",
`location` = " . sqlEscape($_POST['location']) . ",
`telephone` = " . sqlEscape($_POST['telephone']) . "
WHERE id = $_POST[id]";
Use "." instead of "+" to concat strings in PHP.

Related

PHP pg_query update statement

I am trying to updata a database table using pq_query in PHP. I have the following code:
$q = "UPDATE tableName SET ('data1 = " . $data1 . "', data2='" . $data2 . "') WHERE user=".$user;
$success = pg_query($q);
if (!$success) {
$errormessage = pg_last_error();
echo "Error " . $errormessage;
}
I am getting the following error message:
ERROR: syntax error at or near "'data1 = '"
LINE 1: UPDATE tableName SET ('data1 = 10', data2= 20'') WHERE user=
Replace your query with this query
$q = "UPDATE tableName SET data1 = '$data1', data2='$data2' WHERE user='$user'";
Explaination: You should pass variable in single quotes('') if your query in double quotes.
You are using a lot of quotes which it is not understood by PostgreSQL, try simply this :
$q = "UPDATE tableName SET data1 = " . $data1 . ", data2=" . $data2 . " WHERE user=".$user;
Remove those single quotes !

Optimizing PHP script

I have a working script that selects image fields in all tables and empty their values if the physical file doesnt exist.
$query1 = "SELECT table_name,column_name
FROM information_schema.columns
WHERE table_schema='schemaname' AND column_name like '%image%' or column_name='video'";
$result1 = mysql_query($query1) or die(mysql_error() . " -- " . $query1);
while($row1 = mysql_fetch_row($result1)){
if (!strpos($row1[0],'backup') > 0){
$sql = "Select COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME = '".$row1[0]."' AND EXTRA = 'auto_increment'";
$resultcol = mysql_query($sql);
$rowcol = mysql_fetch_row($resultcol);
$query2 = "SELECT " . $row1[1] . ", " .$rowcol[0] . "
FROM " . $row1[0] . "
WHERE " . $row1[1] . " != '' AND " . $row1[1] . " IS NOT NULL
";
echo $query2 . "<br>";
$result2 = mysql_query($query2) or die(mysql_error() . " -- " . $query2);
while ($rowdb = mysql_fetch_row($result2)){
if (!strpos($rowdb[0],'facebook') > 0 && !file_exists($img_root.'/'.$rowdb[0])){
$sql = "UPDATE ".$row1[0]." SET ". $row1[1] . " = '' WHERE " . $rowcol[0]. "= ".$rowdb[1];
echo $sql . "<br><br>";
$delete_count++;
//mysql_query("UPDATE ".$row1[0]." SET ". $row1[1] . " = '' WHERE id = ".$row1["id"]);
}
}
}
}
The script is working fine, but it takes time though, I was wondering if there is a smarter way (more optimized) to get the same function ? Thanks
You have several options.
The first, and IMHO the best option - is to use an ORM -
I recommend Idiorm, Doctrine, or Propel.
Then, you would use something like (in idiorm) fetch_all and loop through that, instead of through the mysql_fetch_row()
Second, you should switch to mysqli -- the functions you are using are deprecated in PHP5.5
Third -- you could just use either mysql_fetch_array or mysql_fetch_all (I'm not sure, but I would be on the latter)
The key thing here is:
Do not loop mysql functions.
Performance wise the problem is that you are looping through a result set, and performing queries for each row.
However with your output it is difficult to eliminate this. Otherwise you might be able to do the whole script in a single SQL statement.
Minimal clean up to just remove one of the selects:-
<?php
$query1 = "SELECT a.table_name, a.column_name, b.COLUMN_NAME AS auto_inc_col
FROM information_schema.columns a
INNER JOIN information_schema.columns b
ON a.table_name = b.table_name AND b.EXTRA = 'auto_increment'
WHERE table_schema='schemaname' AND column_name like '%image%' or column_name='video'";
$result1 = mysql_query($query1) or die(mysql_error() . " -- " . $query1);
while($row1 = mysql_fetch_assoc($result1))
{
if (!strpos($row1['table_name'],'backup') > 0)
{
$query2 = "SELECT " . $row1['column_name'] . ", " .$row1['auto_inc_col'] . "
FROM " . $row1['table_name'] . "
WHERE " . $row1['column_name'] . " != '' AND " . $row1['column_name'] . " IS NOT NULL
";
echo $query2 . "<br>";
$result2 = mysql_query($query2) or die(mysql_error() . " -- " . $query2);
while ($rowdb = mysql_fetch_row($result2))
{
if (!strpos($rowdb[0],'facebook') > 0 && !file_exists($img_root.'/'.$rowdb[0]))
{
$sql = "UPDATE ".$row1['table_name']." SET ". $row1['column_name'] . " = '' WHERE " . $row1['auto_inc_col']. "= ".$rowdb[1];
echo $sql . "<br><br>";
$delete_count++;
//mysql_query("UPDATE ".$row1['table_name']." SET ". $row1['column_name'] . " = '' WHERE id = ".$row1["id"]);
}
}
}
}
?>

How can I get the number of rows in a MySQL table with PHP?

Why is my code returning a 500 Internal Server error on the line $result = mysql_query("SELECT * FROM institutions"); Am I doing something horrifically wrong? All I am trying to do is count the number of rows in a MySQL table (called 'institutions') after I have just added a row to that table.
$institution_sql = "
INSERT INTO `institutions`
(`InstitutionName`, `HeaderPictureID`, `Description`, `DevicesInfo`, `DoingInfo`, `FacebookPage`, `Location`, `TwitterHandle`, `Website`, `CreatedAt`)
VALUES
(" . nz($_POST['TempInstitutionName']) . ", 74, 'N/A', 'N/A', 'N/A', 'N/A', 'On the Internet', 'N/A', 'N/A', NOW())
";
$mysqli->query($institution_sql);
if ($mysqli->errno) {
$dbreturn['status'] = "PASSWORD_FAILURE";
} else {
$dbreturn['status'] = "EXEC_SUCCESS";
$result = mysql_query("SELECT * FROM institutions");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";
$insert_sql = "
INSERT INTO `users`
(`Handle`, `Email`, `FirstName`, `LastName`, `InstitutionID`, `TempInstitutionName`, `TwitterHandle`, `ProfilePictureID`, `HeaderPictureID`, `AccountType`, `CreatedAt`)
VALUES
(" . nz($_POST['Handle']) . ", " . nz($_POST['Email']) . ", " . nz($_POST['FirstName']) . ", " . nz($_POST['LastName']) . ", $num_rows, " . nz($_POST['TempInstitutionName']) . ", " . nz($_POST['TwitterHandle']) . ", " . nz('75') . ", " . nz('74') . ", " . nz($_POST['AccountType']) . ",NOW())
";
$mysqli->query($insert_sql);
if ($mysqli->errno) {
$dbreturn['status'] = "EXEC_FAILURE";
} else {
$dbreturn['status'] = "EXEC_SUCCESS";
$insertid = $mysqli->insert_id;
$password_sql = "
INSERT INTO `passwords`
(`UserID`)
VALUES
('$insertid')
";
$mysqli->query($password_sql);
if ($mysqli->errno) {
$dbreturn['status'] = "PASSWORD_FAILURE";
} else {
$dbreturn['status'] = "EXEC_SUCCESS";
}
} //todo: use a transaction here
}
your problem is that you mixing MYSQLI with MYSQL
rewrite your code using mysqli
$result = $mysqli->query("SELECT * FROM institutions");
$rows = $result->num_rows ;
// and so on ...
you are connecting via mysqli and then you use mysql in your code.
$result = mysql_query("SELECT count(*) FROM institutions");
This will directly return the number of rows.
This link can detail you
http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html
Use
$result = $mysqli->query($institution_sql);
$result->num_rows;
Or for plain old mysql
$result = mysql_query($institution_sql);
mysql_num_rows($result);
Try this:
$result = mysql_query("SELECT count(*) FROM institutions");
MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/select.html
Also this: http://www.w3schools.com/sql/sql_func_count.asp
SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table:
...also, that should be:
VALUES
('" . nz($_POST['TempInstitutionName']) . "', 74
Note the single quotes [unless the 'nz' function takes care of that].

Add MySQL query to PHP file

This is the original MySQL query:
UPDATE jos_bully_table AS jbt1
INNER
JOIN ( SELECT jbt2.bully_concat_name,
COUNT(*) AS b_name_count
FROM jos_bully_table AS jbt2
GROUP
BY jbt2.bully_concat_name
) AS jbt3
ON jbt3.bully_concat_name = jbt1.bully_concat_name
SET jbt1.b_name_count = jbt3.b_name_count
;
It works great when running from phpMyAdmin. I clicked Create PHP Code and this is generated:
$sql = "UPDATE jos_bully_table AS jbt1\n"
. " INNER\n"
. " JOIN ( SELECT jbt2.bully_concat_name,\n"
. " COUNT(*) AS b_name_count\n"
. " FROM jos_bully_table AS jbt2\n"
. " GROUP\n"
. " BY jbt2.bully_concat_name\n"
. " ) AS jbt3\n"
. " ON jbt3.bully_concat_name = jbt1.bully_concat_name\n"
. " SET jbt1.b_name_count = jbt3.b_name_count\n"
. "";
I'm trying to run the same query from a php file, but the db isn't updating.
Here is my php file:
<?php
$database = "xxxxxxxxx" ;
$username = "xxxxxxxxx" ;
$password = "xxxxxxxxx" ;
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
mysql_query($sql);
$sql = "UPDATE jos_bully_table AS jbt1\n"
. " INNER\n"
. " JOIN ( SELECT jbt2.bully_concat_name,\n"
. " COUNT(*) AS b_name_count\n"
. " FROM jos_bully_table AS jbt2\n"
. " GROUP\n"
. " BY jbt2.bully_concat_name\n"
. " ) AS jbt3\n"
. " ON jbt3.bully_concat_name = jbt1.bully_concat_name\n"
. " SET jbt1.b_name_count = jbt3.b_name_count\n"
. "";
echo "<!-- SQL Error ".mysql_error()." -->";
?>
What is wrong with this?
You're running your query string BEFORE you defined it.
$sql = "SELECT ..."
$result = mysql_query($sql) or die(mysql_error());
As well, look into HEREDOCs for defining multi-line strings:
$sql = <<<EOL
SELECT ..
FROM ...
WHERE ...
ORDER BY ..
EOL;
is far more readable than a multi-line concatenation

How to insert multiple checkboxed answers into a database table?

I'm having a huge issue with this database. It connects correctly and with the information from the form's $_POST queries that are being inserted into the table company_info within the correct fields.
Now, I have no idea what I'm doing wrong here, but I keep getting the die error of
"Error querying database".
The database version is: phpMyAdmin 2.6.4-pl3
MySQL: 5.0
Any ideas? I can provide you the rest of the code if needed.
$dbc = mysql_connect('db390590179.db.1and1.com', 'dbo390590179', '*********')
or die('Error connecting to MySQL server.');
mysql_select_db("db390590179", $dbc);
$query = "INSERT INTO company_info (company_name, company_phone, company_contact, company_address, " .
"company_city, company_state, company_zip, " .
"state_living, vehicles, position, " .
"experience, training, hazmat, " .
"require_hazmat, load_nyc, take_truck_home, " .
"have_rider, have_pet, choose_route, " .
"fuel, cash_advance, days_before_home, " .
"log_system, slip_seat, pre_pass, " .
"ez_pass, health_insurance, retirement_plan, " .
"payment_plan, calculate_pay, freight, " .
"loads, home_on_time, idle_time, " .
"equipment_condition, canada)" .
"VALUES ('$company_name', $company_phone', '$company_contact', '$company_address', '$company_city', " .
"'$company_state', '$company_zip', " .
"'$state_living', '$vehicles', '$position', " .
"'$experience', '$training', '$hazmat', " .
"'$require_hazmat', '$load_nyc', '$take_truck_home', " .
"'$have_rider', '$have_pet', '$choose_route', " .
"'$fuel', '$cash_advance', '$days_before_home', " .
"'$log_system', '$slip_seat', '$pre_pass', " .
"'$ez_pass', '$health_insurance', '$retirement_plan', " .
"'$payment_plan', '$calculate_pay', '$freight', " .
"'$loads', '$home_on_time', '$idle_time', " .
"'$equipment_condition', '$canada')";
$result = mysql_query($query, $dbc)
or die('Error querying database.');
mysql_close($dbc);
I think it's because it's missing a quote before the variable $company_phone in your INSERT statement.
just combine the different values within a single quote.
E.g., "'$company_state , $company_zip,' " ."'$state_living , $vehicles, $position, '" ."'$experience, $training, $hazmat, '" ....
this will work perfectly and also include the missing quote in the begining of the *$company_phone* has to be included.
You can remove double quote from each line and combine them. I have removed syntax errors. You can assure that result is getting or not. Try this code.
$dbc = mysql_connect('db390590179.db.1and1.com', 'dbo390590179', '*********')
or die('Error connecting to MySQL server.');
mysql_select_db("db390590179", $dbc);
$query = "INSERT INTO company_info (company_name, company_phone, company_contact, company_address,
company_city, company_state, company_zip,
state_living, vehicles, position,
experience, training, hazmat,
require_hazmat, load_nyc, take_truck_home,
have_rider, have_pet, choose_route,
fuel, cash_advance, days_before_home,
log_system, slip_seat, pre_pass,
ez_pass, health_insurance, retirement_plan,
payment_plan, calculate_pay, freight,
loads, home_on_time, idle_time,
equipment_condition, canada)
VALUES ('$company_name', '$company_phone', '$company_contact', '$company_address', '$company_city',
'$company_state', '$company_zip',
'$state_living', '$vehicles', '$position',
'$experience', '$training', '$hazmat',
'$require_hazmat', '$load_nyc', '$take_truck_home',
'$have_rider', '$have_pet', '$choose_route',
'$fuel', '$cash_advance', '$days_before_home',
'$log_system', '$slip_seat', '$pre_pass',
'$ez_pass', '$health_insurance', '$retirement_plan',
'$payment_plan', '$calculate_pay', '$freight',
'$loads', '$home_on_time', '$idle_time',
'$equipment_condition', '$canada')";
$result = mysql_query($query, $dbc)
or die('Error querying database.');
mysql_close($dbc);
for (int i = 0; i < CheckBoxList1.Items.Count - 1; i++)
{
String str = "";
if (CheckBoxList1.Items[i].Selected)
{
str = CheckBoxList1.Items[i].Text;
con.Open();
string sql =
"Insert into dbtable(Category,BookTitle,Feature,SubCategory)values('" +
DDLCategory.SelectedItem.Text + "','" + TxtBooktitle.Text + "','" +
CheckBoxList1.Items[i].Text + "','" + DDLSubcategory.SelectedItem.Text +
"')";
SqlCommand cmd = new SqlCommand(sql, con);
}
}
Just use DEBUGGER and see how things are working and you should be able to resolve such issues easily.

Categories