PHPform not updating SQL Row - php

I am trying to update sql ROW only using member_id this is my current code.
if ($con = mysql_connect($host, $username, $password)) {
if (mysql_select_db($db_name)) {
$sql = "UPDATE members set
ussd_office = '".$ussd_office."',
ussd_email = '".$ussd_email."',
ussd_e1cell4 = '".$ussd_e1cell4."',
WHERE member_id='$member_id'" ; // This is where my problem lies I presume
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
print_r($_POST);
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
To get the information my form POST and I place it as follow;
$member_id = $_REQUEST['member_id'];
$ussd_surname = $_REQUEST['ussd_surname'];
$member_msisdn = $_REQUEST['member_msisdn'];
$ussd_office = $_REQUEST['ussd_office'];
This is the error I am getting:
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 'WHERE member_id=''' at line 38mysql
err no : 1064
By looking at the error I presume the member_idis not pulled to the WHERE part of my string, and the PHP does not know what row to update. How can I correct my code?

Remove the comma before WHERE.
"UPDATE members set
ussd_office = '".$ussd_office."',
ussd_email = '".$ussd_email."',
ussd_e1cell4 = '".$ussd_e1cell4."'
WHERE member_id='$member_id'"
Your variables in the query and variables from REQUEST dont match.

Related

Return inserted row ID in wordpress wpdb

I want insert some data to a table of the wordpress then return it's auto increase id value.
I do this but both of these has error:
INSERT INTO wp_sho_app_form (job_id, first_name, last_name) VALUES(1, 'Caldwell', 'Estrada');
SELECT LAST_INSERT_ID();
This code word well in MySql but by $wpdb I get this error:
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 'SELECT LAST_INSERT_ID()' at line 1
I call this statement by $wpdb->query and also $wpdb->get_results, but both of them has that error.
I don't want use $wpdb->insert for some reasons and I should use this type of code.
The correct way is to use insert_id.
$lastid = $wpdb->insert_id;
if your make another query its not consistent if you have new entries and a lot of traffic. That can cause wired problems.
And that is only working after insert and you should use them. Don't fight the framework.
You can run a custom query then another to select the last item in the table. If you are using a stand alone php file you need to include the wp-load.php file to get the wordpress functions.
$query = "
INSERT
INTO wp_sho_app_form
(job_id, first_name, last_name)
VALUES
(1, 'Caldwell', 'Estrada')
";
$wpdb->query($query);
$query = "
SELECT *
FROM wp_sho_app_form
ORDER BY col_id desc
LIMIT 1
";
$wpdb->query($query);
There is no way to do multiple query by wpdb. The solution which I could find lastly is using direclty MySqli. I wrote this two function for do it. May be it be useful for sombody. As in ajax wordpress not load so I check to find wp-config fle to get details of connection at first:
public static function run_query($query)
{
$wp_config_path = script_generator::get_wp_config_path();
if($wp_config_path == null){
echo 'Could not found wp_config file!';
return;
}
require_once $wp_config_path;
$mysqli = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result_count = 0;
$result_set = array();
if ($mysqli->multi_query($query)) {
do {
$current_result_count = 0;
$current_result = array();
if ($result = $mysqli->use_result()) {
while ($row = $result->fetch_row()) {
$current_result[$current_result_count] = $row;
$current_result_count++;
}
$result->close();
}
$result_set[$result_count] = $current_result;
if ($mysqli->more_results()) {
$result_count++;
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
return $result_set;
}
function get_wp_config_path(){
$dir = dirname(__FILE__);
do {
if( file_exists($dir."/wp-config.php") ) {
return $dir."/wp-config.php";
}
} while( $dir = realpath("$dir/..") );
return null;
}

MYSQL INSERT syntax error with incorrect line number

I'm currently working on creating a login system, one part of which is of course registration. It's been going smoothly up until this point, where I'm getting an error.
I've researched this as thoroughly as I can, but I can't find the solution as it is giving me an incorrect line number.
The error I'm getting is:
Error: 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 '1' at line 1
My SQL query is
$token = (round(microtime(true) * 1000));
$query = mysql_query("INSERT INTO "
. "`users` "
. "(name, password, email, token) "
. "VALUES "
. "('$_POST[user]'"
. ",'".hash('sha512',$_POST['pass'])."'"
. ",'$_POST[email]'"
. ",'$token')") or die(mysql_error());
if (mysql_query($query) === TRUE) {
//echo "Sucsessfuly registered! Check your email for a confirmation link.";
} else {
echo "Error: " . mysql_error();
}
(this is not the first line of the file, it's the 22d)
When the code runs, even though it throws the error it still is inserting the values into the table correctly.
Also when I run the same query in phpmyadmin, it runs just fine with no errors.
I've been trying to solve this error for the last 3 hours so any help would be appreciated ;)
You're calling mysql_query twice: first with the SQL, and then you're using the result of the query as if it were a query. The error you're getting is because $query is true, which gets turned into 1 when treated as a string.
Either you should just set $query to the SQL string:
$query = "INSERT INTO ...";
if (mysql_query($query)) {
...
} else {
...
}
or you should just check the value of $query:
$query = mysql_query(...);
if ($query) {
...
} else {
...
}

Issue with stored procedure in PHP

I have the following stored procedure that executes correctly when I run my program:
$insertIntoEmployeesProcedure = "
CREATE PROCEDURE EmployeeInsert(name VARCHAR(50),password VARCHAR(50), email VARCHAR(50))
BEGIN
INSERT INTO employees(name,password,email) values(name,password,email);
END";
$returnInsertIntoEmpProc = $conn->query($insertIntoEmployeesProcedure);
if(! $returnInsertIntoEmpProc )
{
die('Could not create insert procedure: ' . $conn->error);
}
else
{
echo "Insert Procedure created successfully<br/>";
}
I then call this procedure in another class when needed:
$insertEmp = mysqli_query($conn, "Call EmployeeInsert('$username','$password', '$email')");
$executeInsertEmp = $conn->query($insertEmp);
if(!$executeInsertEmp )
{
die('Employees not added: ' . $conn->error);
}
else
{
echo "Employees added<br/>";
}
The problem is, when I execute this code, I get the following error
Employees not added: 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 '1' at line 1
The main issue I have with this is that even though it returns this error, the record is still added into the database and everything seems to be working fine. I guess I'm more curious as to why I'm getting this error as clearly I'm overlooking something.
Ah I see what I've done, I seem to have added an additional query which was unnecessary, the line:
$executeInsertEmp = $conn->query($insertEmp);
can be ommited, the check in the if statement is then done on the variable which holds the stored procedure. The following code works:
$insertEmp = mysqli_query($conn, "Call EmployeeInsert('$username','$password', '$email')");
if(!$insertEmp )
{
die('Employees not added: ' . $conn->error);
}
else
{
echo "Employees added<br/>";
}

I am getting a SQL error when trying to update a form in PHP

<?php
$con3=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_error();
}
//$result = mysqli_query($con3,"SELECT * FROM servers");
$updateln = $_POST ['LoggedIn'];
$updateloc = $_POST ['Location'];
$updateos = $_POST ['OperatingSystem'];
$updatesn = $_POST ['ServerName'];
$updatesql="UPDATE servers SET LoggedIn='$updateln', Location='$updateloc'"
. " OperatingSystem = '$updateos' WHERE ServerName = '$updatesn'";
if (!mysqli_query($con3,$updatesql))
{
die('Error: ' . mysqli_error($con3));
}
echo "Record Updated";
I am fairly new to PHP and SQL so I am not really sure what is wrong with the UPDATE sql.
This is the error I am getting
Error: 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 'OperatingSystem = 'ht' WHERE ServerName = 'hr'' at line 1
I have tried other stackoverflow questions and although some people have had problems with this before I can't really see where my code has gone wrong.
You seem to be missing a comma. Replace this:
"UPDATE servers SET LoggedIn='$updateln', Location='$updateloc'"
With this:
"UPDATE servers SET LoggedIn='$updateln', Location='$updateloc',"

Retrieving row from MySQL Database via PHP

Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1"));
echo $row['message'];
Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.
This block of code seems to return nothing - just a blank space. :(
I would be grateful of any suggestions and help. :)
UPDATE:
Code now reads:
<?php
error_reporting(E_ALL);
// Start MySQL Connection
REMOVED FOR SECURITY
// Check if code exists
if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
echo 'Hooray, that works!';
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1")) or die(mysql_error());
echo $row['message'];
}
else {
echo 'That code could not be found. Please try again!';
}
mysql_close();
?>
It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.
Also, don't wrap quotes around integer values in your SQL queries.
if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
die('query failed! ' . mysql_error());
}
$row = mysql_fetch_array($rs);
echo $row['message'];
And the standard "don't use mysql_* functions because deprecated blah blah blah"...
If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.
Some comments:
Don't use mysql_*. It's deprecated. use either mysqli_* functions or the PDO Library
Whenever you enter a value into a query (here, $code), use either mysqli_real_escape_string or PDO's quote function to prevent SQL injection
Always check for errors.
Example using PDO:
//connect to database
$user = 'dbuser'; //mysql user name
$pass = 'dbpass'; //mysql password
$db = 'dbname'; //name of mysql database
$dsn = 'mysql:host=localhost;dbname='.$db;
try {
$con = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
die();
}
//escape code to prevent SQL injection
$code = $con->quote($code);
//prepare the SQL string
$sql = 'SELECT message FROM data WHERE code='.$code.' LIMIT 1';
//do the sql query
$res = $con->query($sql);
if(!$res) {
echo "something wrong with the query!";
echo $sql; //for development only; don't output SQL in live server!
die();
}
//get result
$row = $res->fetch(PDO::FETCH_ASSOC);
//output result
print_r($row);

Categories