I have a weird problem with my sql script.
I have a string
$query = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message)
VALUES ('93361357', '2162', '27761144734', 'Hoekom');";
But when I execute that string it inserts it to the table but eventid stays 0, if I run that exact command in cmd it works perfectly?
Any ideas why this is not inserting all the values?
Edit Full code
<?php session_start();
$link = mysql_connect("localhost", "username", "password"); //removed u and p for posting
if (!$link)
die("Couldn't connect to MySQL");
mysql_select_db("db", $link) //removed db name for posting
or die ("Couldn't open smss:" . mysql_error());
$id = $_SESSION['id'];
$message = $_REQUEST['promo_message'];
$timeToSend = $_REQUEST['timeToSend'];
$dateToSend = $_REQUEST['dateToSend'];
if(isset($_REQUEST['input_cell']))
{
$receiver = $_REQUEST['input_cell'];
if($receiver != '')
{
$response_string = sendSMSPortalSchedule($message, $receiver, $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
$query1 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message');";
mysql_query($query1);
echo mysql_error();
}
}
if(isset($_REQUEST['single_cell']))
{
$receiver = $_REQUEST['single_cell'];
if($receiver != 'none')
{
$response_string = sendSMSPortalSchedule($message, $receiver, $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
$query2 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message');";
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
mysql_query($query2);
echo mysql_error();
}
}
if(isset($_REQUEST['sento_group']))
{
$array = $_REQUEST['sento_group'];
foreach($array as $receiver)
{
if($receiver != 'none')
{
$query = 'SELECT cell_number FROM cell_groups WHERE group_id ="'.$receiver.'"';
$result2 = mysql_query($query) or die('Fail');
while($row=mysql_fetch_array($result2))
{
$response_string = sendSMSPortalSchedule($message, $row['cell_number'], $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
$to = $row['cell_number'];
$query3 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$to', '$message');";
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
mysql_query($query3);
echo mysql_error();
}
}
}
}
}
This is the table
id = INT
eventid = BIGINT(20)
bus_id = INT
cell_num = VARCHAR
sms_message = VARCHAR
The SQL command itself is correct. The problem must be elsewhere.
Firstly, are you sure that the values of your parameters are correct? Try outputting the query after variable interpolation to see if it is correct:
$query1 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message')";
echo $query1;
Seondly I notice that in you have INSERTs in multiple places. Make sure all of them work as expected. Remember that the one you think is executing may be different from the one that is actually executing.
I found the problem, the service I was using got changed to return XML where it usually just returned an integer, this caused me to try and insert XML into my BIGINT field, which is not possible. So in the end the problem was caused by an updated service that didn't notify clients about changes.
Related
I have my table setup as shown in the image below.
When I try and run the following code to insert the values into the database I get the error:
FAIL: INSERT INTO Betfairodds
(Horse,Back,Lay,TimeformTR)VALUES( 'Intrepid','5.5', '5.9',
'0')
Would anyone be able to help, as I have tried to debug the code.
//loop through each individual card
foreach ($getdropdown2 as $dropresults) {
$horse = preg_replace('/\h*[^ a-zA-Z].*$/m', '', trim($dropresults->childNodes->item(8)->textContent));
$back = trim(GetBetween($dropresults->childNodes->item(18)->textContent, 'Back', '£'));
$lay = trim(GetBetween($dropresults->childNodes->item(20)->textContent, 'Lay', '£'));
$sql = "INSERT INTO `Betfairodds` (`Horse`,`Back`,`Lay`,`TimeformTR`)VALUES( '$horse','$back', '$lay', '0')";
$res = mysqli_query($db, $sql);
if (!$res) {
echo PHP_EOL . "FAIL: $sql";
trigger_error(mysqli_error($db), E_USER_ERROR);
}
}
I removed the quotes ' from 0 because it is defined as int in the schema and of-course added space right before VALUES ..try this:
$sql = "INSERT INTO `Betfairodds` (`Horse`,`Back`,`Lay`,`TimeformTR`) VALUES( '$horse','$back', '$lay', 0)";
Your statement is wrong. You should not put single quotes on the data fields. so it should be like:
$sql = "INSERT INTO `Betfairodds` (Horse,Back,Lay,TimeformTR)VALUES( '$horse','$back', '$lay', '0')";
I use this piece of php to insert/update mysql db. Please see my question in the comment part at corresponding lines. Thanks.
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database! Please try again later.");
mysql_select_db($dbname);
arr = array();
if (strcasecmp($actionIn, 'insert') == 0) {
$query = "INSERT INTO $usertable (id, fname, lname) VALUES ('$id', '$fname', 'lname'";
$result = mysql_query($query) or die(mysql_error()); //AT THIS STEP, I would get error message if I insert a duplicated id into table, no following json_encode would not print out, that's what I want.
if ($result) {
$arr['inserted'] = 'true';
}
exit(json_encode($arr));
}
if (strcasecmp($actionIn, 'update') == 0) {
$query = "UPDATE $usertable SET id = '$id', fname = '$fname', lname = '$lname' WHERE id = '$id'";
$result = mysql_query($query) or die(mysql_error()); //AT THIS STEP, if I update a non-existent id, I don't get error, and the following steps continue to execute. I want the error info or return me a false.
if ($result) {
$arr['updated'] = 'true';
}
exit(json_encode($arr));
}
I also tried these, but both num_rows and affected_rows return 0. why?
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
$aff_cnt = $result->affected_rows;
printf("Result set aff %d rows.\n", $aff_cnt);
Thanks for your help!
If UPDATE doesn't match anything to update it will simply return. This is not an error. To find out whether it's updated anything use mysql_affected_rows().
Note: mysql_*() doesn't support the OOP form, so you should use mysql_affected_rows(), which should work for your second case above.
This will give you:
if (strcasecmp($actionIn, 'update') == 0) {
$query = "UPDATE $usertable SET id = '$id', fname = '$fname', lname = '$lname' WHERE id = '$id'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_affected_rows() !== 0) {
$arr['updated'] = 'true';
}
Side note: mysql_*() is deprecated and will be removed. You should use mysqli or PDO for new code.
I'm working on a form in PHP that inserts data to MySQL, but before the data is inserted there is a field that must be checked in another table before inserting. If this value exist in the other table, then the data is inserted in the main table, if not, then data is not inserted.
Here is my code to insert the data:
$host = "localhost";
$username = "root";
$password = "";
$db_name = "forms";
$tbl_name = "table1";
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$nombre = $_POST['nombre'];
$apellido = $_POST['apellido'];
$cedula = $_POST['cedula'];
$email = $_POST['email'];
$telefono = $_POST['telefono'];
$establecimiento = $_POST['establecimiento'];
$codigo = $_POST['codigo'];
$sql = " INSERT INTO $tbl_name(Nombre, Apellido, Cedula, Email, Telefono, Establecimiento, Codigo)VALUES('$nombre', '$apellido', '$cedula', '$email', '$telefono', '$establecimiento', '$codigo')";
$result = mysql_query($sql);
if ($result) {
echo "Your data was sent";
} else {
echo "You inserted a wrong code";
}
?>
<?php
// close connection
mysql_close();
?>
So, what I need is to check the value $codigo in table2, if exists, then insert $codigo in table1 with the other values. This is where I'm stuck.
All you really need to do is this.
// Check if Codigo already exists in table2
$codigo = mysql_real_escape_string($_POST['codigo']);
$result = mysql_query("SELECT Codigo FROM table2 WHERE Codigo = '$codigo'");
if (!mysql_num_rows($result)) {
// Go ahead and insert everything in table1
$data = array(
'Nombre' => $_POST['Nombre'],
'Apellido' => $_POST['apellido'],
'Cedula' => $_POST['cedula'],
'Email' => $_POST['email'],
'Telefono' => $_POST['telefono'],
'Establecimiento' => $_POST['establecimiento'],
'Codigo' => $_POST['codigo']
);
// Make sure all the data is safe for entry into the database
foreach ($data as $key => $val) {
$data[$key] = "'" . mysql_real_escape_string($val) . "'";
}
$fields = implode(', ', array_keys($data));
$values = implode(', ', array_values($data));
$result = mysql_query("INSERT INTO table1 ($fields) VALUES ($values)");
echo 'Your data was sent';
} else {
echo 'Codigo already exists in table2';
}
But please note there are many ways of doing this that are far better and more efficient. For one, I would recommend you use PHP's mysqli functions rather than the deprecated mysql ones (http://www.php.net/manual/en/book.mysqli.php)
More importantly, you don't look like you're protecting your queries against SQL injection at all. Please read up on this, but it's usually just a need for real_escape_string() on any value you are inserting into a SQL query.
Simply do a SELECT query on the other table with the data you are checking for and then if mysql_num_rows() > 0 you do an insert. Something like below
$query = "SELECT * FROM otherTable WHERE infoIsSame";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$sql=" INSERT INTO $tbl_name(Nombre, Apellido, Cedula, Email, Telefono, Establecimiento, Codigo)VALUES('$nombre', '$apellido', '$cedula', '$email', '$telefono', '$establecimiento', '$codigo')";
$result=mysql_query($sql);
if($result){
echo "Your data was sent";
}else {
echo "You inserted a wrong code";
}
}else{
echo "Not present in Other database";
}
One approach is to let the INSERT statement do the check for you:
INSERT INTO $tbl_name (Nombre, Apellido, Cedula, Email, Telefono, Establecimiento, Codigo)
SELECT '$nombre', '$apellido', '$cedula', '$email', '$telefono', '$establecimiento', '$codigo'
FROM table2
WHERE table2.Codigo = '$codigo'
LIMIT 1
Then check the number of rows inserted mysql_affected_rows() to determine whether a row was inserted or not. This fewer round trips to the database, for the "normative" case where you expect a row to be inserted.
NOTE: avoid using mysql_ functions and use mysqli_ or PDO instead.
This is my code:
$q=mysql_query("SELECT * FROM `table1` WHERE name like '%$searchText%'");
while($e=mysql_fetch_assoc($q))
//$output[]=$e;
//echo $e['NAME'];
{
$name = $e['NAME'];
$brand = $e['BRAND'];
$category = $e['CATEGORY'];
$query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
$result = mysql_query($query) or die("Unable to insert because : " . mysql_error());
}
Since in "BRAND", there may be some data like "First's Choice".
In this case, I cannot insert to database due to error.
How can I insert data that contain single quotes?
Thx
you need to use mysql_real_escape_string on the value, which you should be doing anyway. That should properly escape your value for insertion.
$name = mysql_real_escape_string($e['NAME']);
$brand = mysql_real_escape_string($e['BRAND']);
$category = mysql_real_escape_string($e['CATEGORY']);
$query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
Use mysql_real_escape_string
You must use :
$brand = mysql_real_escape_string($brand)
See PHP Documentation.
string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL ] )
Escapes special characters in
the unescaped_string, taking into account the current character set of
the connection so that it is safe to place it in a mysql_query(). If
binary data is to be inserted, this function must be used. (..)
Try below code
$q=mysql_query("SELECT * FROM `table1` WHERE name like '%$searchText%'");
while($e=mysql_fetch_assoc($q))
//$output[]=$e;
//echo $e['NAME'];
{
$name = $e['NAME'];
$brand = mysql_real_escape_string($e['BRAND']);
$category = $e['CATEGORY'];
$query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
$result = mysql_query($query) or die("Unable to insert because : " . mysql_error());
}
There are two ways of accomplishing that. You can first run an escape string on it:
$newbrand = mysql_real_escape_string($brand);
and insert $newbrand. When you call it, you have to do strpslashes($newbrand);
OR you could do:
$search = array("'");
$newbrand = str_replace($search,'',$brand);
I was pulling my hair to solve this, finally i am ok with this solution. Try this
I get the error: Column 'Time' cannot be null when using the query below, it works fine the first time when there is no duplicate but then when trying to update again I get the error: Column 'Time' cannot be null
mysql_query("
INSERT INTO
$table(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time=Time+INTERVAL $time SECOND
Videos=Videos+'$videos',
Credits=Credits+'$credits'
",
$conn
);
Hope you can spot my error as I am new to this, thanks!
Here is some more of my code:
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME, $conn);
// Error checking
if(!$conn) {
die('Could not connect ' . mysql_error());
}
// Localize the GET variables
$user = isset($_GET['username']) ? $_GET['username'] : "";
$time = isset($_GET['time']) ? $_GET['time'] : "";
$videos = isset($_GET['videos']) ? $_GET['videos'] : "";
$credits = isset($_GET['credits']) ? $_GET['credits'] : "";
// Protect against sql injections
$user = mysql_real_escape_string($user);
$time = mysql_real_escape_string($time);
$videos = mysql_real_escape_string($videos);
$credits = mysql_real_escape_string($credits);
$secret = mysql_real_escape_string($secret);
// Insert
$retval = mysql_query("
INSERT INTO
$table(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = DATE_ADD(IFNULL(Time,now()),INTERVAL '$time' SECOND),
Videos = Videos+'$videos',
Credits = Credits+'$credits'
",
$conn
);
// End Query
if($retval) {
echo "Success! Updated $user with Time: $time - Videos: $videos - Credits: $credits";
} else {
echo "<b>ERROR:</b><br>" . mysql_error();
}
mysql_close($conn);
It should be:
mysql_query("
INSERT INTO
$table(Username, `Time`, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = DATE_ADD(IFNULL(`Time`,now()),INTERVAL '$time' SECOND)
,Videos = Videos+'$videos'
,Credits = Credits+'$credits'
",
$conn
);
Don't forget to put single quotes around all injected variables, otherwise mysql_real_escape_string will not protect you.
See:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
If there's no duplicate, then this query will do an insert, and the Time value will be null, as no value was ever set. Null + anything is null, hence the error.
Try ... Time = COALESCE(Time, 0) + INTERVAL $time SECOND or similar to get aroun dit.