I'm currently having an issue where my query returns a success however there is no actual update that occurs when I check my SQL database. Oddly enough, when I copy the same exact query into phpMyAdmin, a response is successfully returned and the query works just fine, the rows are updated. (Note: I'm well aware of the high risk of SQL injection, however mysqli_escape_string isn't working for some reason so I'll worry about that when I go into the production stage.)
script.php
$fave = json_decode($_POST['af']);
$unfave = json_decode($_POST['uf']);
$fave = "'".implode("','", $fave)."'";
$unfave = "'".implode("','", $unfave)."'";
if ($fave !== "''"){
$fq = "UPDATE post SET fave='1' WHERE 'an_id' IN ($fave) AND bid='$bizusr' AND fave='0'";
$r_fq = mysqli_query($GLOBALS["___mysqli_ston"], $fq);
$ar_fq = mysqli_affected_rows($GLOBALS["___mysqli_ston"]);
} else {
$r_fq = 1;
$ar_fq = 0;
}
if ($unfave !== "''"){
$ufq = "UPDATE post SET fave='0' WHERE 'an_id' IN ($unfave) AND bid='$bizusr' AND fave='1'";
$r_ufq = mysqli_query($GLOBALS["___mysqli_ston"], $ufq);
$ar_ufq = mysqli_affected_rows($GLOBALS["___mysqli_ston"]);
} else {
$r_ufq = 1;
$ar_ufq = 0;
}
if ($r_fq && $r_ufq){
$output = json_encode(array('type'=>'error', 'text' => "Favourites have been updated successfully. You've added $ar_fq favorites and removed $ar_ufq favorites." ));
die($output);
}
if (!$r_fq && $r_ufq){
$output = json_encode(array('type'=>'error', 'text' => "We've successfully favorited $ar_fq links, however there was an issue in unfavoriting some links, try refreshing." ));
die($output);
}
if ($r_fq && !$r_ufq){
$output = json_encode(array('type'=>'error', 'text' => "We've successfully unfavorited $ar_ufq links, however there was an issue in favoriting some links, try refreshing." ));
die($output);
}
if (!$r_fq && !$r_ufq){
$output = json_encode(array('type'=>'error', 'text' => "There was an error in updating your favorited links." ));
die($output);
}
// $un = mysqli_prepare($GLOBALS["___mysqli_ston"], "UPDATE analytics SET fave='0' WHERE an_id IN (?) AND bid= ? AND fave='1'");
// $fa = mysqli_prepare($GLOBALS["___mysqli_ston"], "UPDATE analytics SET fave='1' WHERE an_id IN (?) AND bid= ? AND fave='0'");
// mysqli_stmt_bind_param($un, 'ss', $unfave, $blockject);
// $a = mysqli_stmt_execute($un);
// mysqli_stmt_close($un);
// mysqli_stmt_bind_param($fa, 'ss', $fave, $blockject);
// $b = mysqli_stmt_execute($fa);
// mysqli_stmt_close($fa);
The variables $fave and $unfave would return values like so: 'abcd123','dcba321','hello123', which would make the query look like so:
UPDATE post SET fave='0' WHERE 'an_id' IN ('abcd123','dcba321','hello123') AND bid='$bizusr' AND fave='1';
Now, entering the query into phpMyAdmin works just fine, but when doing it through php, the response returns a success however no rows are actually updated, so I'm not sure what is going on as my php error.log is as clean as a whistle.
Also, if you're wondering what my require_once connection.php file looks like which connects me to the database, it is the following:
$link = ($GLOBALS["___mysqli_ston"] = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD));
if(!$link) {
die('Failed to connect to server: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
}
//Select database
$db = ((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE " . constant('DB_DATABASE')));
if(!$db) {
die("Unable to select database");
}
Silly me, I'm not sure why it was returning a successful query, however wrapping the column id an_id in single quotes was the issue
Related
I have a php script that runs alongside advanced installer. The Mysql doesn't work and I need to use Mysqli functions instead. I have already got the connection working fine with Mysqli but the other functions don't seem to be working.
The Script essentially just needs to confirm that the serial no entered is valid and check it against how many times it has been used. I'f there is a way of making this more simple I'm all ears!I'm not a professional php developer but the support from advanced installer said he doesn't know how to change it to mysqli.
<?php
define('LICENSE_VALID', '601');
define('LICENSE_INVALID', '602');
# Fill our vars and run on cli
# $ php -f db-connect-test.php
$dbname = 'mydb';
$dbuser = '';
$dbpass = '';
$dbhost = '127.0.0.1';
$clients_tbl_name = 'clients';
$sn_tbl_col = 'serial_no';
$lic_no_tbl_col = 'license_no';
$val_no_tbl_col = 'validations_no';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
mysqli_select_db($conn, $dbname) or die("Could not open the db '$dbname'");
// serial validation results
$serial_invalid = 0; // invalid serial
$serial_ok = 1; // valid serial
$val_exceeded = 2; // valid serial but maximum number of validations exceeded
function ServerResponse($valResult, $posted_serial = '', $lang_id = 1033)
{
global $serial_invalid, $serial_ok, $val_exceeded;
$msg_sep = "\n";
// load error messages from your database, using "$lang_id" for localization (optional)
if($posted_serial == '')
return LICENSE_INVALID . $msg_sep . "Missing Serial Number !";
switch($valResult)
{
case $val_exceeded:
return LICENSE_INVALID . $msg_sep . 'Maximum number of validations exceeded for Serial Number: ' . $posted_serial;
case $serial_ok:
return LICENSE_VALID;
default:
return LICENSE_INVALID . $msg_sep . 'Serial Number: ' . $posted_serial . ' is invalid !';
}
}
if(isset($_POST['sn']) && trim($_POST['sn']) != '')
{
// get the serial number entered by the installing user in the "UserRegistrationDlg" dialog
$sn = trim($_POST['sn']);
// get the system language ID of the user's machine
// (you can use this parameter to display a localized error message taken from your database)
$languageid = (int) $_POST['languageid'];
// prepare SQL statement
$sn_query = sprintf("SELECT `%s`, `%s`, `%s` FROM `%s` WHERE `%s` = '%s'",
$sn_tbl_col, $lic_no_tbl_col, $val_no_tbl_col,
$clients_tbl_name, $sn_tbl_col, mysqli_real_escape_string($conn ,$_POST['sn']));
// execute query
$result = #mysqli_query($sn_query, $conn);
// get result set size
if(#mysqli_num_rows($result) == 0)
{
// serial number NOT found in database => issue error response
echo ServerResponse($serial_invalid, $sn, $languageid);
die();
}
else // serial number was found in database
{
// fetch the result row as an associative array
$row = #mysqli_fetch_array($result, MYSQLI_ASSOC);
if(!$row)
{
// issue error response
echo ServerResponse($serial_invalid, $sn, $languageid);
die();
}
// increment the validations_no column
$inc_val_no_query = sprintf("UPDATE `%s` SET `%s` = `%s` + 1 WHERE `%s` = '%s'",
$clients_tbl_name, $val_no_tbl_col, $val_no_tbl_col,
$sn_tbl_col, mysqli_real_escape_string($conn ,$_POST['sn']));
// execute the update query
#mysqli_query($inc_val_no_query, $conn);
// check whether the user has reached maximum number of validations
$license_no = (int) $row[ $lic_no_tbl_col ];
$validation_no = (int) $row[ $val_no_tbl_col ];
if($validation_no >= $license_no)
{
// issue error response => maximum number of validations exceeded
echo ServerResponse($val_exceeded, $sn, $languageid);
die();
}
else
{
// issue SUCCESS response
echo ServerResponse($serial_ok, $sn, $languageid);
die();
}
}
}
else
{
// issue error response
echo ServerResponse($serial_invalid);
die();
}
?>
Thanks!
Jason
The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.
I have this code is working fine my application gets the data with json and is all fine but when I insert special characters like ñ which I need to get I can't have been told that I should use the utf8_encode but I just don't know how to apply it here since.
<?php
require_once(dirname(__FILE__).'/ConnectionInfo.php');
//Set up our connection
$connectionInfo = new ConnectionInfo();
$connectionInfo->GetConnection();
if (!$connectionInfo->conn)
{
//Connection failed
echo 'No Connection';
}
else
{
if (isset($_POST['mod']) && isset($_POST['lec']) && isset($_POST['clase']))
{
$mod = $_POST['mod'];
$lec = $_POST['lec'];
$clase = $_POST['clase'];
//Create query to retrieve all contacts
$query = 'SELECT TituloEjercicio,PreguntaEjercicio,Opcion1Ejercicio,Opcion2Ejercicio,Opcion3Ejercicio,Opcion4Ejercicio,EstaCorrectaEjercicio FROM ejercicios WHERE QueModulo = ? and QueLeccion = ? and Queclase = ?';
$params = array($mod,$lec,$clase);
$stmt = sqlsrv_query($connectionInfo->conn, $query,$params);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$contacts = array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$contact = array("lbl_variable_cuestionario_titulo" => $row['TituloEjercicio'],
"lbl_variable_pregunta" => $row['PreguntaEjercicio'],
"opcion1" => $row['Opcion1Ejercicio'],
"opcion2" => $row['Opcion2Ejercicio'],
"opcion3" => $row['Opcion3Ejercicio'],
"opcion4" => $row['Opcion4Ejercicio'],
"EstaCorrecta" => $row['EstaCorrectaEjercicio']
);
//Add the contact to the contacts array
array_push($contacts, $contact);
}
//Echo out the contacts array in JSON format
echo json_encode($contacts);
sqlsrv_close($connectionInfo->conn);
}
}
sqlsrv_close($connectionInfo->conn);
}
sqlsrv_close($connectionInfo->conn);
?>
If your issue lies with pushing non-latin characters to MySQL then you might just have to configure your database to use UTF8. There are good tutorials online that show you how to do that.
I have to search if a postal code is in my database, my table is called "test" there is only one table in my database with one column and one row, the column is named "codes", and there is an only row with the INT 63000, i have a form in my website where client enter a code, and it called a .php file which check if the value is missing or present in the database, i don't know PHP so it's hard for me... :( And my code don't work :(
SOLVED : THIS IS THE WORKING CODE :
<?php session_start(); ?>
<?php
if($_POST['code-postal'] === '') {
$hasError = true;
} else {
$variable = $_POST['code-postal'];
$code = intval($variable);
}
mysql_connect('xxxxxxxxx', 'xxxxxxxxxxxx', 'xxxxxxxxxxxx')
or die("I cannot connect to the database because: " . mysql_error());
mysql_select_db('xxxxxxxxxx');
$code = mysql_real_escape_string($code);
$sql = "SELECT COUNT(*) AS total_count FROM test WHERE codes='$code'";
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
$data = mysql_fetch_assoc($req);
if($data['total_count'] == 1) {
$verif = true;
}
else {
$verif = false;
}
// on ferme la connexion à mysql
mysql_close();
?>
$sql = "SELECT COUNT(*) AS total_count FROM test WHERE codes='$code'";
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
$data = mysql_fetch_assoc($req);
if($data['total_count'] == 1) {
$verif = true;
}
else {
$verif = false;
}
Here is the working code.
mysql_query would return result set. You will need to use mysql_fetch_assoc function to retrieve data from that.
I guess you would have more rows in table in future, because as you mentioned in table that you have only one table with one column and one row, then there is no need of database, you can directly compare values.
Im trying to write a simple prgram that the server can get data from client.
I write a simple code in my script
var str = "testString";
$.post("http://anonymous.comze.com/test1.php", { string: str });
in the server,
$var = $_POST['string']; // this fetches your post action
$sql2 = "INSERT INTO afb_comments VALUES ('3',$var)";
$result2= mysql_query($sql2,$conn);
The question is var is always null. The sql2 can be executed if I change $var into "1111" for example,
but if I put $var, it doesn't work. Can anyone give some advice?
your are passing string to the query so it should be
$var = $_POST['string']; // this fetches your post action
$sql2 = "INSERT INTO afb_comments VALUES ('3','".$var."')";
$result2= mysql_query($sql2,$conn);
please also check datatype of the that column.
Use this example and learn from this code how to get data
Or
use can also use this link:
http://api.jquery.com/jQuery.get/
$user and $pass should be set to your MySql User's username and password.
I'd use something like this:
JS
success: function(data){
if(data.status === 1){
sr = data.rows;
}else{
// db query failed, use data.message to get error message
}
}
PHP:
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$databaseName = "movedb";
$tableName = "part parameters";
$con = mysql_pconnect($host, $user, $pass);
$dbs = mysql_select_db($databaseName, $con);
//get the parameter from URL
$pid = $_GET["pid"];
if(empty($pid)){
echo json_encode(array('status' => 0, 'message' => 'PID invalid.'));
} else{
if (!$dbs){
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t connect to the db'));
}
else{
//connection successful
$sql = "SELECT `Processing Rate (ppm)` FROM `part parameters` WHERE `Part Number` LIKE `" . mysqli_real_escape_string($pid) . "`"; //sql string command
$result = mysql_query($sql) or die(mysql_error());//execute SQL string command
if(mysql_num_rows($result) > 0){
$rows = mysql_fetch_row($result);
echo json_encode(array('status' => 1, 'rows' => $rows["Processing Rate (ppm)"]);
}else{
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t find processing rate for the give PID.'));
}
}
}
?>
As another user said, you should try renaming your database fields without spaces so part parameters => part_parameters, Part Number => part_number.